본문 바로가기
Algorithm/leetcode

[leetcode] 844.Backspace String compare

by 세류오 2023. 8. 27.

https://leetcode.com/problems/backspace-string-compare/description/

 

Backspace String Compare - LeetCode

Can you solve this real interview question? Backspace String Compare - Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the tex

leetcode.com

 

🧐 문제 이해

두 개의 문자열 s와 t가 주어진다

s와 t의 문자열에는 '#'이 포함되어있고 

'#'은 백스페이스 키의 역할을 하고 있다

- 단 백스페이스시 공백이라면 그대로 공백을 유지

이 때 입력된 s와 t에서 #을 계산한 결과 값이 같다면 true, 틀리다면 false를 리턴

 

🚀 풀이

Stack을 이용

char형태로 for문을 반복하여 stack에 push

'#'이 들어올 때 isEmpty()를 실행 

- true라면 continue를 사용

- false라면 stack에 pop

 

위의 진행을 s와 t반복 실행

 

각각 stack에 쌓인 값을 문자열 변수에 다시 저장

마지막에 equals()로 값을 비교하여 true, false를 리턴

 

 

class Solution {
    public boolean backspaceCompare(String s, String t) {
        Stack<Character> sData = new Stack<>();
        Stack<Character> tData = new Stack<>();
        String sfull = "";
        String tfull = "";

        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);

            if(c == '#') {
                if(sData.isEmpty()){
                    continue;
                } else {
                    sData.pop();
                }
            } else {
                sData.push(c);
            }
        }
        for(int i = 0; i < sData.size(); i++){
            sfull += sData.get(i);
        }

        for(int i = 0; i < t.length(); i++){
            char c = t.charAt(i);

            if(c == '#') {
                if(tData.isEmpty()){
                    continue;
                } else {
                    tData.pop();
                }
            } else {
                tData.push(c);
            }
        }
        for(int i = 0; i < tData.size(); i++){
            tfull += tData.get(i);
        }


        if(sfull.equals(tfull)) {
            return true;
        } else 
            return false;
    }
}