Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. We repeatedly make duplicate removals on S until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.

Example 1:
Input: "abbaca"
Output: "ca"
Explanation: 
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Method1. 自己写的烂方法
class Solution {
    public String removeDuplicates(String S) {
        while(!S.equals(helper(S))) S = helper(S);
        return S;
        //return helper(S);
    }

    private String helper(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < s.length(); i++) {
            if(i < s.length()- 1 && s.charAt(i+1) != s.charAt(i)) {
                sb.append(s.charAt(i));
            } else if(i < s.length() - 1 && s.charAt(i+1) == s.charAt(i)) {
                i++;
            } else if(i == s.length() - 1) {
                sb.append(s.charAt(i));
            }
        }
        return new String(sb);
    }
}

Method2. stack
class Solution {
    public String removeDuplicates(String S) {
        Stack<Character> stack = new Stack<>();
        for(int i = 0; i < S.length(); i++) {
            if(stack.isEmpty()) stack.push(S.charAt(i));
            else if(!stack.isEmpty() && S.charAt(i) == stack.peek()){
                stack.pop();
            } else stack.push(S.charAt(i));
        }

        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()) sb.append(stack.pop());
        return new String(sb.reverse());
    }
}

results matching ""

    No results matching ""