LeetCode——1047. Remove all adjacent duplicates in the string

Title description:

Given a string S consisting of lowercase letters, the duplicate deletion operation will select two adjacent and identical letters and delete them. Repeat the deduplication operation on S until it can no longer be deleted. The final string is returned after all the deduplication operations are completed. The answer is guaranteed to be unique.

prompt:

  • 1 <= S.length <= 20000
  • S consists of lowercase English letters only.

Example:

  • Input: "abbaca"
  • Output: "ca"
  • Explanation:
    For example, in "abbaca", we can delete "bb". Since the two letters are adjacent and the same, this is the only duplicate item that can be deleted at this time. Then we get the string "aaca", of which only "aa" can perform the deduplication operation, so the final string is "ca".

code show as below:

class Solution {
    
    
    public String removeDuplicates(String S) {
    
    
        int n = S.length();
        char[] ch = S.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
    
    
            if (stack.isEmpty() || ch[i] != stack.peek()) {
    
    
                stack.push(ch[i]);
            } else {
    
    
                stack.pop();
            }
        }
        StringBuilder builder = new StringBuilder();
        for (Character c : stack) {
    
    
            builder.append(c);
        }
        return builder.toString();
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114267802