All adjacent duplicate entries deleted string

String S is given by the lowercase letters, delete duplicates and selects two identical letters adjacent to, and remove them.

Performed on the S repeatedly duplicates deletion, can not continue until deleted.

Returns the final string after the completion of all duplicates deletion. The only answer guarantee.

Enter: "abbaca"
Output: "ca"
interpretation:
for example, in "abbaca", we can remove the "bb" as the two adjacent letters and the same, this is the only duplicates this time can perform delete operations. After we get the string "aaca", which has only "aa" can perform delete duplicates, so the final string is "ca".

public String removeDuplicates(String S) {
        char[] x = S.toCharArray();

        Character[] dest = new Character[x.length];
        for (int i = 0; i < x.length; i++) {
            dest[i] = Character.valueOf(x[i]);
        }

        ArrayList<Character> list = new ArrayList<>(Arrays.asList(dest)) ;


        boolean hasdupli = true;
        while (hasdupli){

            int beginsize = list.size() ;

            for(int i=0 ;i<list.size()-1;i++){
               if(list.get(i)==list.get(i+1)){
                   list.remove(i);
                   list.remove(i);
                   break;
               }
            }

            int endsize = list.size();

            if(beginsize==endsize){
                hasdupli = false ;
            }else {
                hasdupli = true ;
            }
        }

        StringBuilder sb = new StringBuilder() ;
        for(int j=0 ;j<list.size();j++){
            sb.append(list.get(j)) ;
        }
        return sb.toString();
    }

 

Guess you like

Origin blog.csdn.net/u013317653/article/details/91432666