leetcode-844-easy

发布时间 2023-04-14 22:23:08作者: iyiluo

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 text will continue empty.

Example 1:

Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
Example 2:

Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".
Example 3:

Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".
Constraints:

1 <= s.length, t.length <= 200
s and t only contain lowercase letters and '#' characters.
Follow up: Can you solve it in O(n) time and O(1) space?

思路一:用栈实现

    public boolean backspaceCompare(String s, String t) {
        char[] chars1 = s.toCharArray();
        char[] chars2 = t.toCharArray();

        Stack<Character> stack1 = new Stack<>();
        for (char c : chars1) {
            if (c == '#' && !stack1.isEmpty()) {
                stack1.pop();
            } else if (c != '#') {
                stack1.push(c);
            }
        }

        Stack<Character> stack2 = new Stack<>();
        for (char c : chars2) {
            if (c == '#' && !stack2.isEmpty()) {
                stack2.pop();
            } else if (c != '#') {
                stack2.push(c);
            }
        }

        return stack1.equals(stack2);
    }

思路二: 从字符串后面往前面遍历,可以省去栈的调用

    public boolean backspaceCompare2(String s, String t) {
    char[] chars1 = s.toCharArray();
    char[] chars2 = t.toCharArray();

        StringBuilder s1 = new StringBuilder();
        int count = 0;
        for (int i = chars1.length - 1; i >= 0; i--) {
            char c = chars1[i];
            if (c == '#') {
                count++;
            } else {
                if (count == 0) {
                    s1.append(c);
                } else {
                    count--;
                }
            }
        }

        StringBuilder s2 = new StringBuilder();
        count = 0;
        for (int i = chars2.length - 1; i >= 0; i--) {
            char c = chars2[i];
            if (c == '#') {
                count++;
            } else {
                if (count == 0) {
                    s2.append(c);
                } else {
                    count--;
                }
            }
        }

        return s1.toString().equals(s2.toString());
    }