LeetCode - 1544. Make The String Great(String, Stack)

YAMAMAMO·2022년 11월 10일
0

LeetCode

목록 보기
81/100

문제

Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.

https://leetcode.com/problems/make-the-string-great/description/

Example 1:

Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".

Example 2:

Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""

Example 3:

Input: s = "s"
Output: "s"

풀이

class Solution {
    public String makeGood(String s) {
        if(s.length()==1) return s;
        Stack<Character> stack = new Stack<>();
        char[] c = s.toCharArray();
        stack.push(c[0]);

        for(int i=1;i<c.length;i++){
            if(stack.empty()){
                stack.push(c[i]);
            }else{
                char tmp = stack.peek();
                if(compareChar(tmp,c[i])){
                    // System.out.println("팝"+stack.peek());
                    stack.pop();
                }else{
                    stack.push(c[i]);
                    // System.out.println("픽 - "+stack.peek());
                }
            }
        }

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

        StringBuilder res = new StringBuilder();
        while(!stack.empty()){
            res.append(stack.peek());
            stack.pop();
        }
        return res.reverse().toString();
        
    }

    //true - a,b 가 서로 각각 소문자 대문자 이고 대소 구별 없이 같은 문자, false 그 외의 경우
    public boolean compareChar(char a, char b){
        boolean aFlag = a >= 'a' && a <= 'z' ? true : false;
        boolean bFlag = b >= 'a' && b <= 'z' ? true : false;
        if(aFlag!=bFlag){
            return Character.toUpperCase(a)==Character.toUpperCase(b);
        }else{
            return false;
        } 
    }
}
profile
안드로이드 개발자

0개의 댓글