Your method does a lot of unnecessary work.
The problem can be solved by repeating a line once and comparing each character with the one that precedes it:
public static StringBuilder singleOccurence(String s)
{
StringBuilder sb = new StringBuilder();
if (s.length() > 0) {
char prev = s.charAt(0);
sb.append(prev);
for (int i = 1; i < s.length(); ++i) {
char cur = s.charAt(i);
if (cur != prev) {
sb.append(cur);
prev = cur;
}
}
}
return sb;
}
This method has linear time complexity.
source
share