Note that after backspacing an empty text, the text will continue empty.
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".
Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".
class Solution {
public boolean backspaceCompare(String s, String t) {
return backspacing(s).equals(backspacing(t));
}
public String backspacing(String word)
{
Stack<Character> stack = new Stack<>();
for(int i = 0; i< word.length(); i++)
{
if(word.charAt(i) != '#')
{
stack.push(word.charAt(i) );
}else
{
if(!stack.isEmpty())
{
stack.pop();
}
}
}
// 注意这里可以直接将stack转化成String
return String.valueOf(stack);
}
}
public class Solution {
public bool BackspaceCompare(string s, string t) {
int sback=0,tback=0;
int i=s.Length-1,j=t.Length-1;
char hash='#';
while(i>=0 || j>=0)
{
//find first non # character in s string
while(i>=0)
{
if(s[i]==hash)
{
sback++;
i--;
}
else if(sback>0)
{
sback--;
i--;
}
else
break;
}
//find first non # character in t string
while(j>=0)
{
if(t[j]==hash)
{
tback++;
j--;
}
else if (tback>0)
{
tback--;
j--;
}
else
break;
}
if(i>=0 && j>=0 && s[i]!=t[j])
return false;
if((i>=0) != (j>=0))
return false;
i--;
j--;
}
return true;
}
}