File tree 1 file changed +45
-0
lines changed 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/backspace-string-compare/
2
+
3
+ class Solution :
4
+ def backspaceCompare (self , s : str , t : str ) -> bool :
5
+ i = len (s ) - 1 # Traverse from the end of the strings
6
+ j = len (t ) - 1
7
+ # The number of backspaces required till we arrive at a valid character
8
+ bs = 0 # count of backspace for s
9
+ bt = 0 # count of backspace for t
10
+
11
+ while i >= 0 or j >= 0 :
12
+ while i >= 0 : # count bs
13
+ if s [i ] == "#" :
14
+ bs += 1
15
+ i -= 1
16
+ elif bs > 0 and s [i ] != "#" :
17
+ bs -= 1
18
+ i -= 1
19
+ else :
20
+ break
21
+
22
+ while j >= 0 : # count bt
23
+ if t [j ] == "#" :
24
+ bt += 1
25
+ j -= 1
26
+ elif bt > 0 and t [j ] != "#" :
27
+ bt -= 1
28
+ j -= 1
29
+ else :
30
+ break
31
+ # Also ensure that both the character indices are valid. If it is not valid, it means that we are comparing a "#" with a valid character.
32
+ if i >= 0 and j < 0 : return False
33
+ if i < 0 and j >= 0 : return False
34
+
35
+ if s [i ] != t [j ]: return False
36
+
37
+ i -= 1
38
+ j -= 1
39
+
40
+
41
+ return True
42
+
43
+
44
+ # Time Complexity: O(N)
45
+ # Space Complexity: O(1)
You can’t perform that action at this time.
0 commit comments