0
Remove 3 consecutive duplicate from string
INPUT: aabbbaccddddc OUTPUT: cdc
2 Réponses
+ 1
write down step by step how you solve the problem on a piece of paper. take each step and turn it into a instruction in code.
+ 1
Output should be "ccdc" logically.
public static String removeTripleOccurrence(String s) {
String str=s;
for (int i=0; i<str.length(); i++) {
char ch=str.charAt(i);
try {
if ((str.charAt(i+1)==ch)&&(str.charAt(i+2)==ch))
return str.substring(0, i)+str.substring(i+3);
} catch (StringIndexOutOfBoundException e) { return null; }
}
return null;
}
public static void main(String[] args) {
String str = "aabbbaccddddc";
String ans=str, lastAns="";
for (;;) {
ans = removeTripleOccurrence(ans);
if (ans == null) {
ans=lastAns;
break;
}
else lastAns=ans;
}
if (ans.equals("")) ans = str;
System.out.println("Result = "+ans);
}