class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def build(string):
res = []
for char in string:
if char != '#':
res.append(char)
elif res:
res.pop()
return res
return build(S) == build(T)
class Solution {
public:
bool backspaceCompare(string S, string T) {
return build(S) == build(T);
}
private:
string build(const string& str) {
string res;
for (char c : str) {
if (c != '#')
res.push_back(c);
else if (!res.empty())
res.pop_back();
}
return res;
}
};
class Solution {
public boolean backspaceCompare(String S, String T) {
return build(S).equals(build(T));
}
private String build(String str) {
StringBuilder res = new StringBuilder();
for (char c : str.toCharArray()) {
if (c != '#')
res.append(c);
else if (res.length() > 0)
res.deleteCharAt(res.length() - 1);
}
return res.toString();
}
}
var backspaceCompare = function(S, T) {
function build(str) {
let res = [];
for (let c of str) {
if (c !== '#') {
res.push(c);
} else if (res.length) {
res.pop();
}
}
return res.join('');
}
return build(S) === build(T);
};
Given two strings S
and T
, return true
if they are equal when both are typed into empty text editors. In these editors, the #
character means a backspace, so it erases the character before it (if any). After processing all the characters in both strings, compare the results.
#
acts as a backspace and removes the previous character, if one exists.true
if both processed strings are identical, false
otherwise.#
character.The problem asks us to simulate how typing works in a basic text editor with backspace support. The most direct approach is to process each string and simulate the effect of backspaces, then compare the final results.
#
, we remove the last added character (if any).This approach is both intuitive (like using a stack or a list) and easy to implement. Optimization can be considered once the core logic is understood.
We can solve this problem by simulating the typing process for both strings:
#
, append it to the list.#
and the list is not empty, remove (pop) the last character from the list.S
and T
using the above simulation.true
, else return false
.This method is straightforward and leverages the stack/list structure to simulate the backspace behavior efficiently.
Let's consider the example: S = "ab#c"
, T = "ad#c"
S
:
T
:
true
.O(N + M)
where N
and M
are the lengths of S
and T
.O(N + M)
due to storing the processed strings.O(1)
(not shown above).O(N + M)
.O(1)
if not storing the processed strings.The Backspace String Compare problem is efficiently solved by simulating the effect of backspaces using a stack or list. By processing each string and handling backspaces as they appear, we can easily compare the final results. The approach is intuitive, leverages basic data structures, and can be optimized further if needed. This method highlights the power of simulating real-world processes with simple programming constructs.