两种解法:
1.用stack存储,重新构建字符串,比较是否相等。
2.双指针,有后向前遍历,此解法空间复杂度为O(1)。
JAVA
class Solution { public boolean backspaceCompare(String S, String T) { return helpback(S).equals(helpback(T)); } public Stack<Character> helpback(String str){ Stack<Character> stack = new Stack(); for(int i = 0; i < str.length(); i++){ if(str.charAt(i) == '#'){ if(stack.size() != 0)stack.pop(); continue; } stack.push(str.charAt(i)); } return stack; } }
class Solution { public boolean backspaceCompare(String S, String T) { int i = S.length()-1; int j = T.length()-1; int iskip = 0; int jskip = 0; while(i >= 0 || j >= 0){ while(i >= 0){ //!!!找到比较的位置 if(S.charAt(i) == '#'){ iskip++; i--; } else if(iskip > 0){ iskip--; i--; } else break; } while(j >= 0){ //!!!找到比较的位置 if(T.charAt(j) == '#'){ jskip++; j--; } else if(jskip > 0){ jskip--; j--; } else break; } // If two actual characters are different if(i >= 0 && j >= 0 && S.charAt(i) != T.charAt(j)) return false; // If expecting to compare char vs nothing if((i >=0 ) != (j >= 0)) return false; i--; j--; } return true; } }
Python3
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: return self._back(S) == self._back(T) def _back(self, str): stack = [] for i in range(len(str)): if str[i] == '#': if stack: stack.pop() continue stack.append(str[i]) return stack
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: i = len(S)-1 j = len(T)-1 iskip = 0 jskip = 0 while i >= 0 or j >= 0: while i >= 0: if S[i] == '#': iskip += 1 i -= 1 elif iskip > 0: iskip -= 1 i -= 1 else: break while j >= 0: if T[j] == '#': jskip += 1 j -= 1 elif jskip > 0: jskip -= 1 j -= 1 else: break if i >= 0 and j >= 0 and S[i] != T[j]: return False if (i >= 0) != (j >= 0): return False i -= 1 j -= 1 return True