最初,我如何解决此CodeWars问题的方法是使用:StringUtils.countMatches();
但是,我想知道是否可以对字符使用XOR?
这里是我到目前为止的内容,但是它没有通过测试,我很沮丧。
static String encode(String word) {
String test = word.toLowerCase();
char[] temp = test.toCharArray();
String sol = "";
for (char y : temp) {
if (duplicate(temp, y) == true)
sol += "(";
else
sol += ")";
}
return sol;
}
public static boolean duplicate(char[] values, char check) {
for (char x : values) {
check ^= x;
if (check == 0)
return false;
}
return true;
}
下面的方法用'('
编码字符串中的重复字符(从当前位置开始!),用')'
编码非重复字符:
static String encode(String word) {
String test = word.toLowerCase();
char[] cc = test.toCharArray();
StringBuilder sol = new StringBuilder();
for (int i = 0; i < cc.length; i++) {
char c = cc[i];
boolean duplicateFound = false;
for (int j = i+1; j < cc.length; j++) {
char x = cc[j];
if ((x ^ c) == 0) {
duplicateFound = true;
break;
}
}
sol.append(duplicateFound ? '(' : ')');
}
return sol.toString();
}
// test
System.out.println(encode("abcabc")); // prints: ((()))
System.out.println(encode("abcdad")); // prints: ())())
System.out.println(encode("abcdfg")); // prints: ))))))
下面的方法通过了检测所有唯一字符的CodeWars测试:
public static boolean hasUniqueChars(String str) {
String test = str.toLowerCase();
char[] cc = test.toCharArray();
for (int i = 0; i < cc.length; i++) {
char c = cc[i];
for (int j = i+1; j < cc.length; j++) {
char x = cc[j];
if ((x ^ c) == 0) {
return false;
}
}
}
return true;
}