这道题很简单,其实是一个Stack的问题, 但是不用Stack,用一个StringBuilder就可以解决,时间复杂度和空间复杂度都是O(n).

    public String removeDuplicates(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (sb.length() > 0 && s.charAt(i) == sb.charAt(sb.length() - 1)) {
                sb.deleteCharAt(sb.length() - 1);
            } else {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }

 Stack Solution:

class Solution {
    public String removeDuplicates(String s) {
        Stack<Character> stk = new Stack<>();
        for(int i=0;i<s.length();i++){
            if(stk.isEmpty()){
                stk.push(s.charAt(i));
                continue;
            }
            if(s.charAt(i)!=stk.peek()){
                stk.push(s.charAt(i));
            }
            else{
                stk.pop();
            }
        }
        StringBuilder res = new StringBuilder();
        for(char c:stk){
            res.append(c);
        }
        return res.toString();
    }
}

 

posted on 2022-01-03 11:50  阳光明媚的菲越  阅读(20)  评论(0编辑  收藏  举报