java - Removing Consecutive Characters in each Iteration shows Unexpected error -


how remove consecutive characters @ each iteration.. below screenshot explains question more details

q1

mysolution

  1. initially checked whether there consecutive characters. if yes,then,remove consecutive characters , when there no consecutive characters add remaining characters string.

  2. if no consecutive characters increment it.


public static void print(){     string s1="aabcccdee";  have taken sample test case     string s2="";     for(int i=0;i<s1.length();){         if(s1.charat(i)==s1.charat(i+1)){             while(s1.charat(i)==s1.charat(i+1)){                 i++;             }             for(int j=i+1;j<s1.length();j++){                 s2=s2+s1.charat(j);             }         s1=s2;           }         else         i++;     }     system.out.println(s1); } 

output shown

an infinite loop 

expected output give sample

bd 

can guide me how correct?

you can use string::replacefirts regex (.)\1+ means matche charater (.) followed \1 1 or more time + empty.
in case want replace first first have check input, if after each iteration still contain more 1 consecutive characters or not, in case can use pattern , matcher :

string[] strings = {"aabcccdee", "abbabba", "abbd "}; (string str : strings) {     pattern pattern = pattern.compile("([a-z])\\1");      // while input contain more 1 consecutive char make replace     while (pattern.matcher(str).find()) {         // note : use replacefirst instead of replaceall         str = str.replacefirst("(.)\\1+", "");     }     system.out.println(str); } 

outputs

aabcccdee -> bd abbabba   -> abbd      -> ad 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -