(LC) 1047. Delete all adjacent duplicates in the string

1047. Remove all adjacent duplicates in a string

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.

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".

prompt:

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

answer:

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

Guess you like

Origin blog.csdn.net/weixin_45567738/article/details/114603994