I am trying to improve my coding skills and stumbled upon this task: "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." Below you can see my solution, where the follwing error appears:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1 ( ^
I do not quite get why this error appears, I am not even using any kind of Group Matching/Pattern etc. I thought I know why it may appears, but the fix didn't work (its the if close which is commented in the code below)
My code may seem stupid to you, I tried to solve the given task by first creating a hashmap where i store every char and assign its key with the value of ( or ) depending how many times it occures in the given word. Afterwords, I iterate through my whole HashMap and replace all Occurences of the keys by their value, I thought that might be efficient. At least you know now why I am trying to achieve, and it works for Strings which do not contain special characters like whitespaces and brackets.
Oh and btw, it really frustates me that I am unable to find the problem on my own, even after reading problems which seem related to mine. If you have a general suggestion for me how to more succesfully approach these kind of problems, I would be so happy to hear your suggestion!
import java.util.HashMap;
public class DuplicateEncoder {
static String encode(String word) {
HashMap<Character, Character> replaceMap = new HashMap<>();
char[] charArray = word.toLowerCase().toCharArray();
for (char c : charArray) {
if (!replaceMap.containsKey(c)) {
int count = 0;
for (char c2 : charArray) {
if (c2 == c) {
count++;
}
}
if (count > 1) {
replaceMap.put(c, ')');
} else {
replaceMap.put(c, '(');
}
}
}
String result = word.toLowerCase();
for (char c : replaceMap.keySet()) {
// if(result.indexOf(c)>=0) {
result = result.replaceAll(Character.toString(c), Character.toString(replaceMap.get(c)));
// }
}
return result;
}
public static void main(String[] args){
String s = "Prespecialized";
System.out.println(DuplicateEncoder.encode(s));
s = " ()( ";
System.out.println(DuplicateEncoder.encode(s));
}
}
You use regex here:
result = result.replaceAll(Character.toString(c), Character.toString(replaceMap.get(c)));
// }
Check String.replaceAll
docs. When your character is '(' you are getting this exception. Try String.replace(char, char)
instead