LeetCode 844. Backspace String Compare
考点 | 难度 |
---|---|
Simulation | Easy |
题目
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.
思路
用helper function把s
和t
转换成不带#
的string,然后比较两个string。stack转换到string用的是String.valueOf(ans);
答案
public boolean backspaceCompare(String S, String T) {
return build(S).equals(build(T));
}
public String build(String S) {
Stack<Character> ans = new Stack();
for (char c: S.toCharArray()) {
if (c != '#')
ans.push(c);
else if (!ans.empty())
ans.pop();
}
return String.valueOf(ans);
}