[LeetCode] 1047. Remove All Adjacent Duplicates In String
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".
Note:
1 <= S.length <= 20000
S
consists only of English lowercase letters.
删除字符串中的所有相邻重复项。
题目不难理解,就是请你删除字符串中有相邻字母的部分。根据例子的解释,不难想到需要用 stack 处理。遍历 input 字符串,判断当前遍历到的字符是否和栈顶字符一样,若一样,就把栈顶元素 pop 出来,同时当前字符也就略过不处理了。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public String removeDuplicates(String s) { 3 Stack<Character> stack = new Stack<>(); 4 for (char c : s.toCharArray()) { 5 if (!stack.isEmpty() && stack.peek().equals(c)) { 6 stack.pop(); 7 } else { 8 stack.push(c); 9 } 10 } 11 12 StringBuilder sb = new StringBuilder(); 13 while (!stack.isEmpty()) { 14 sb.append(stack.pop()); 15 } 16 return sb.reverse().toString(); 17 } 18 }
相关题目
1047. Remove All Adjacent Duplicates In String