Found a JavaScript assignment on Codewars.com:
The goal of this exercise is to convert a string to a new string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
Examples:
"din" => "(((" "recede" => "()()()" "Success" => ")())())" "(( @" => "))(("
I did the assignment in Java, and came up with below code. I want to know is this the write way to code or is there a better way? If so please let me know.
private static String duplicateEncode(String word) {
String encodeString = "";
String decodedString = word.toLowerCase();
for (int i = 0; i < decodedString.length(); i++) {
if (decodedString.substring(i + 1, decodedString.length())
.contains(String.valueOf(decodedString.charAt(i)))
|| decodedString.substring(0, i).contains(String.valueOf(decodedString.charAt(i)))) {
encodeString += ")";
} else {
encodeString += "(";
}
}
return encodeString;
}