본문 바로가기
Problem Solving/LeetCode

[LeetCode] 844. Backspace String Compare - Java

by graycode 2026. 10. 25.

• 문제 링크

 

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

 

• 풀이 코드

public class Solution {

    public boolean backspaceCompare(String s, String t) {
        int i = s.length() - 1, j = t.length() - 1, a = 0, b = 0;
        while (i >= 0 || j >= 0) {
            while (i >= 0) {
                if (s.charAt(i) == '#') {
                    a++;
                    i--;
                } else if (a > 0) {
                    a--;
                    i--;
                } else break;
            }

            while (j >= 0) {
                if (t.charAt(j) == '#') {
                    b++;
                    j--;
                } else if (b > 0) {
                    b--;
                    j--;
                } else break;
            }

            if ((i >= 0 && j >= 0 && s.charAt(i) != t.charAt(j)) || i-- >= 0 != j-- >= 0) return false;
        }

        return true;
    }

}

댓글