Skip to content

Commit b6e511a

Browse files
authored
Create 0844-backspace-string-compare.kt
1 parent a2c65a1 commit b6e511a

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// Two pointer solution, time O(n) and space O(1)
2+
class Solution {
3+
fun backspaceCompare(s: String, t: String): Boolean {
4+
5+
fun nextValidChar(str: String, _index: Int): Int {
6+
var backspace = 0
7+
var index = _index
8+
while (index >= 0) {
9+
if (backspace == 0 && str[index] != '#')
10+
break
11+
else if (str[index] == '#')
12+
backspace++
13+
else
14+
backspace--
15+
index--
16+
}
17+
18+
return index
19+
}
20+
21+
var index_s = s.lastIndex
22+
var index_t = t.lastIndex
23+
while (index_s >= 0 || index_t >= 0) {
24+
index_s = nextValidChar(s, index_s)
25+
index_t = nextValidChar(t, index_t)
26+
27+
val char_s = if (index_s >= 0) s[index_s] else '?'
28+
val char_t = if (index_t >= 0) t[index_t] else '?'
29+
if (char_s != char_t)
30+
return false
31+
index_s--
32+
index_t--
33+
}
34+
35+
return true
36+
}
37+
}
38+
39+
// Stack solution, time O(n) and space O(n)
40+
class Solution {
41+
fun backspaceCompare(s: String, t: String): Boolean {
42+
val s1 = LinkedList<Char>()
43+
val s2 = LinkedList<Char>()
44+
45+
for (c in s) {
46+
if (c == '#') {
47+
if (s1.isNotEmpty())
48+
s1.removeLast()
49+
} else {
50+
s1.addLast(c)
51+
}
52+
}
53+
54+
for (c in t) {
55+
if (c == '#') {
56+
if (s2.isNotEmpty())
57+
s2.removeLast()
58+
} else {
59+
s2.addLast(c)
60+
}
61+
}
62+
63+
return s1.joinToString("") == s2.joinToString("")
64+
}
65+
}
66+
67+
// Another style of two pointer solution, same idea, without calling methods, time O(n) and space O(1)
68+
class Solution {
69+
fun backspaceCompare(s: String, t: String): Boolean {
70+
var i = s.lastIndex
71+
var j = t.lastIndex
72+
var steps = 0
73+
74+
while (true) {
75+
steps = 0
76+
while (i >= 0 && (steps > 0 || s[i] == '#')) {
77+
steps += if (s[i] == '#') 1 else -1
78+
i--
79+
}
80+
81+
steps = 0
82+
while (j >= 0 && (steps > 0 || t[j] == '#')) {
83+
steps += if (t[j] == '#') 1 else -1
84+
j--
85+
}
86+
87+
if (i >= 0 && j >= 0 && s[i] == t[j]) {
88+
i--
89+
j--
90+
} else {
91+
break
92+
}
93+
}
94+
95+
return i == -1 && j == -1
96+
}
97+
}

0 commit comments

Comments
 (0)