学堂 学堂 学堂公众号手机端

LeetCode-Backspace String Compare

lewis 1年前 (2024-04-02) 阅读数 5 #技术


Description:
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 <= S.length <= 2001 <= T.length <= 200S and T only contain lowercase letters and ‘#’ characters.

Follow up:

Can you solve it in O(N) time and O(1) space?

题意:判断两个字符串是否相同;字符串中包含符号’#’,表示前一个字符为空字符,例如对于字符串"ab#"=>“a”;

解法:我们主要需要解决的就是如果处理空字符;很容易想到可以利用栈来实现,每当遇到字符’#'时,将栈顶的元素出栈,否则将此字符入栈;因为最后还要返回一个新的字符串,所以我们使用StringBuilder来模拟栈;

Java
class Solution {
public boolean backspaceCompare(String S, String T) {
return removeBackspace(S).equals(removeBackspace(T));
}
private String removeBackspace(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '#') {
if (sb.length() == 0) continue;
sb.deleteCharAt(sb.length() - 1);
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门