LeetCode 1047. Remove All Adjacent Duplicates In String

1047. Remove All Adjacent Duplicates In String (remove all duplicate entries adjacent string)

 

Links: https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/

 

topic:

 

  String S is given by the lowercase letters, delete duplicates and selects two identical letters adjacent to, and remove them.

  Performed on the S repeatedly duplicates deletion, can not continue until deleted.

  Returns the final string after the completion of all duplicates deletion. The only answer guarantee.

 

  Example:

  Enter: "abbaca"
  Output: "ca"
  interpretation:
  for example, in "abbaca", we can remove the "bb" as the two adjacent letters and the same, this is the only duplicates this time can perform delete operations. After we get the string "aaca", which has only "aa" can perform delete duplicates, so the final string is "ca".
 

  prompt:

  . 1 <= s.length <= 20000
  S only by the lower case letters.

 

Ideas:

  I am here to help the stack, the letters go into, and if the next one and the same on to the stack, or on the stack, and finally help stringbuffer transpose it to produce a string. The memory of more than 100% but more than 30%, it is annoying.

  (Idea changed my code standards .......)

 

Code:

 

 1   public static String removeDuplicates(String S) {
 2     char[] ch = S.toCharArray();
 3     Stack stack = new Stack();
 4     int i = 0;
 5     while (i < ch.length) {
 6       if (stack.empty()) {
 7         stack.push(ch[i]);
 8       } else if (stack.peek().equals(ch[i])) {
 9         stack.pop();
10       } else {
11         stack.push(ch[i]);
12       }
13       i++;
14     }
15 
16     StringBuilder sb = new StringBuilder();
17     while (!stack.empty()) {
18       sb.append(stack.pop());
19     }
20     return sb.reverse().toString();
21   }

 

Guess you like

Origin www.cnblogs.com/blogxjc/p/11220403.html