Backspace String Compare-LeetCode#844

844. Backspace String Compare

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

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 = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:

Input: S = "a#c", T = "b"Output: false
Explanation: S becomes "c" while T becomes "b".

Note:

  1. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. S and T only contain lowercase letters and '#' characters.

退格字符串比较,给定两个字符串 S 和 T ,如果它们在空文本编辑器中输入时它们相等则返回。#表示退格符。
循环遍历字符串中的每个字符,比较 是否为 “#” ,使用 StringBuilder,并输出最后结果。

public class BackspaceStringCompare {
    public boolean backspaceCompare(String S, String T) {
        return backString(S).equals(backString(T));
    }
    private String backString(String temp) {
        StringBuilder res = new StringBuilder();
        char[] chars = temp.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != ("#").toCharArray()[0]) {
                res.append(chars[i]);
            }else if (chars[i] == ("#").toCharArray()[0]){
                if (res.length() > 0){
                    res.deleteCharAt(res.length() - 1);
                }
            }
        }
        return res.toString();
    }
    public static void main(String[] args) {
        BackspaceStringCompare backspaceStringCompare = new BackspaceStringCompare();
        backspaceStringCompare.backspaceCompare("ab##", "c#d#");
    }
}
文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部