Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb6e511a

Browse files
authored
Create 0844-backspace-string-compare.kt
1 parenta2c65a1 commitb6e511a

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+
classSolution {
3+
funbackspaceCompare(s:String,t:String):Boolean {
4+
5+
funnextValidChar(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+
elseif (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+
returnfalse
31+
index_s--
32+
index_t--
33+
}
34+
35+
returntrue
36+
}
37+
}
38+
39+
// Stack solution, time O(n) and space O(n)
40+
classSolution {
41+
funbackspaceCompare(s:String,t:String):Boolean {
42+
val s1=LinkedList<Char>()
43+
val s2=LinkedList<Char>()
44+
45+
for (cin s) {
46+
if (c=='#') {
47+
if (s1.isNotEmpty())
48+
s1.removeLast()
49+
}else {
50+
s1.addLast(c)
51+
}
52+
}
53+
54+
for (cin 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+
classSolution {
69+
funbackspaceCompare(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]=='#')1else-1
78+
i--
79+
}
80+
81+
steps=0
82+
while (j>=0&& (steps>0|| t[j]=='#')) {
83+
steps+=if (t[j]=='#')1else-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)

[8]ページ先頭

©2009-2025 Movatter.jp