LeetCode - 1047. Remove All Adjacent Duplicates In String(String, Stack)

YAMAMAMO·2022년 11월 11일
0

LeetCode

목록 보기
82/100

문제

You are given a string s consisting of lowercase English 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 can be proven that the answer is unique.

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

Example 1:

Input: s = "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".

Example 2:

Input: s = "azxxzy"
Output: "ay"

풀이

class Solution {
    public String removeDuplicates(String s) {
        if(s.length()==1) return s;
        
        StringBuilder res = new StringBuilder();
        Stack<Character> stack = new Stack<>();

        for(char c : s.toCharArray()){
            if(stack.isEmpty()) stack.push(c);
            else{
                if(stack.peek()==c) stack.pop();
                else stack.push(c);
            }
        }

        if(stack.isEmpty()) return "";

        while(!stack.isEmpty()){
            res.append(stack.pop());
        }

        return res.reverse().toString();
    }
}
profile
안드로이드 개발자

0개의 댓글