1047--Remove All Adjacent Duplicates In String

public class RemoveAllAdjacentDuplicatesInString {
    /*
    解法一:栈
     */
    public String removeDuplicates(String S) {
        Stack<Character> stack=new Stack<>();
        for (char c:S.toCharArray()){
            if (stack.isEmpty()||c!=stack.peek())
                stack.push(c);
            else
                stack.pop();
        }
        StringBuilder stringBuilder=new StringBuilder();
        for (Character character:stack)
            stringBuilder.append(character);
        return stringBuilder.toString();
    }
    /*
    解法二:StringBuilder模拟栈。
     */
    public String removeDuplicates2(String S) {
     StringBuilder stringBuilder=new StringBuilder();
     int length=0;
     for (char c:S.toCharArray()){
        if (length!=0&&c==stringBuilder.charAt(length-1))
            stringBuilder.deleteCharAt(length-- -1);
        else {
            stringBuilder.append(c);
            length++;
        }
     }
     return stringBuilder.toString();
    }
}

 

posted @ 2019-09-08 13:06  张玉昊  阅读(265)  评论(0编辑  收藏  举报