0

Remove 3 consecutive duplicate from string

INPUT: aabbbaccddddc OUTPUT: cdc

17th Feb 2017, 5:04 PM
Mohd Shahid Ameen
Mohd Shahid Ameen - avatar
2 Antworten
+ 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.
17th Feb 2017, 6:19 PM
Michael W
Michael W - avatar
+ 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); }
18th Feb 2017, 6:36 AM
Jian-hua Yeh
Jian-hua Yeh - avatar