LeetCode 1047. Remove All Adjacent Duplicates In String (删除字符串中的所有相邻重复项)
题目标签:Stack
利用stack, 把每一个 char 存入 stack 的时候,如果和stack 里的 char 一样,把stack 里的 char 去除。
具体看code。
Java Solution:
Runtime: 14 ms, faster than 73.38%
Memory Usage: 41.9 MB, less than 100.00%
完成日期:02/15/2020
关键点:stack
class Solution { public String removeDuplicates(String S) { char [] chars; Stack<Character> stack = new Stack<>(); for(char c : S.toCharArray()) { // if find the same char, remove it from stack if(!stack.empty() && c == stack.peek()) { stack.pop(); } else { // put it into stack stack.push(c); } } chars = new char[stack.size()]; for(int i=chars.length - 1; i >= 0; i--) { chars[i] = stack.pop(); } return new String(chars); } }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/