1047--Remove All Adjacent Duplicates In String

Posted zhangyuhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    }
}

 

以上是关于1047--Remove All Adjacent Duplicates In String的主要内容,如果未能解决你的问题,请参考以下文章

1047--Remove All Adjacent Duplicates In String

LC-1047 Remove All Adjacent Duplicates In String

LeetCode --- 1047. Remove All Adjacent Duplicates In String 解题报告

LeetCode --- 1047. Remove All Adjacent Duplicates In String 解题报告

1047. Remove All Adjacent Duplicates In String做题报告

Leetcode 1047. Remove All Adjacent Duplicates In String