Remove adjacent duplicate characters in a String(java) i.e input:aaaabbbccdbbaae output: abcdbae
java, string
Solution
Your method is doing a lot of unnecessary work.
The problem can be solved by iterating over the string once and comparing each character to 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.
Problem
my code does not give expected output,but dry run works fine.please give a look where is the problem ``` public static StringBuffer singleOccurence(String s) { StringBuffer sb = new StringBuffer(s); int length=s.length(); for(int i=0; i< length ; i++) { for(int j=i; i<length&&j<length ; j++) { if(sb.charAt(i)!=sb.charAt(j+1)) i=j+1; else sb.deleteCharAt(j+1); } } return sb; } ``` also gives StringIndexOutOfBounds