LeetCode1047—删除字符串中的所有相邻重复项(java版)

题目描述:

标签:栈  

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

代码:

 思路分析:

想到用栈解决,每个元素压入前都与栈顶的元素比较,如果相同就可以消除。但这里不是直接造一个栈对象,是用stringbuffer stack实现了栈,定义一个指向栈顶的指针top。

获取栈顶的元素用的是stack.charAt(top)

删除栈顶的元素用的是stack.deleteCharAt(top)

压入栈的元素用的是stack.append(ch)

class Solution {
    public String removeDuplicates(String S) {
        StringBuffer stack = new StringBuffer();
        int top = -1;
        for(int i = 0;i < S.length();i++){
            char ch = S.charAt(i);
            if(top >= 0 && stack.charAt(top) == ch){
                stack.deleteCharAt(top);
                top--;
            }else{
                stack.append(ch);
                top++;
            }
        }
        return stack.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40840749/article/details/114680427
今日推荐