classSolution{publicbooleanbackspaceCompare(String s,String t){Stack<Character> stackS =newStack<>();Stack<Character> stackT =newStack<>();// Building stacksfor(char c : s.toCharArray()){if(c !='#'){
stackS.push(c);}elseif(!stackS.isEmpty()){
stackS.pop();}}for(char c : t.toCharArray()){if(c !='#'){
stackT.push(c);}elseif(!stackT.isEmpty()){
stackT.pop();}}// If the same, then stack size is the sameif(stackS.size()!= stackT.size())returnfalse;// Size will be changing while poppingint size = stackS.size();for(int i =0; i < size;++i){if(stackS.pop()!= stackT.pop())returnfalse;}returntrue;}}
Code(使用2 pointers)
使用這個方法,這個題目應該就不是Easy了🤣
# Helper functiondefnextValidChar(str, index):
backspace =0while index >=0:# Until skipped backspaced itemif backspace ==0andstr[index]!="#":breakelifstr[index]=="#":
backspace +=1else:
backspace -=1
index -=1return index
index_s, index_t =len(s)-1,len(t)-1# Until char still existwhile index_s >=0or index_t >=0:
index_s = nextValidChar(s, index_s)
index_t = nextValidChar(t, index_t)
char_s = s[index_s]if index_s >=0else""
char_t = t[index_t]if index_t >=0else""if char_s != char_t:returnFalse
index_s -=1
index_t -=1returnTrue