Reputation: 502
I am currently solving the following hackerrank problem https://www.hackerrank.com/challenges/reduced-string/problem, in where given a string I have to eliminate pairs of characters that are the same.
My code is as follows:
static String super_reduced_string(String s){
for (int i = 0; i < s.length()-1; i++) {
if (s.charAt(i) == s.charAt(i+1)) {
s = s.substring(0, i) + s.substring(i+2);
i = 0;
}
}
if (s.length() == 0) {
return("Empty String");
} else {
return(s);
}
}
It works in most cases, however with certain testcases such as if the string is "baab", the code outputs "bb" (baab should be simplified to bb and then to an empty string) instead of an empty string, however I don't see why this is the case.
Upvotes: 2
Views: 126
Reputation: 10161
At the end of the for
-loop i
is incremented. So if you want the loop to begin at the start again after a match you need to set i
to -1
so the next loop run starts with i==0
.
static String super_reduced_string(String s){
for (int i = 0; i < s.length()-1; i++) {
if (s.charAt(i) == s.charAt(i+1)) {
s = s.substring(0, i) + s.substring(i+2);
i = -1; // so after the ++ at the end of the loop, the next loop-run will have i==0.
}
}
if (s.length() == 0) {
return("Empty String");
} else {
return(s);
}
}
Tampering with a loop counter is always a bit error prone. So I recommend avoiding it.
Upvotes: 7