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

Commit5b1a71f

Browse files
authored
Create 2108-find-first-palindromic-string-in-the-array.kt
1 parent0617997 commit5b1a71f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// For every word, check that its reverse equals it
2+
classSolution {
3+
funfirstPalindrome(words:Array<String>):String {
4+
words.forEach { word->
5+
if (word== word.reversed())
6+
return word
7+
}
8+
9+
return""
10+
}
11+
}
12+
13+
// For every word, check that its reverse equals it but using two pointers
14+
classSolution {
15+
funfirstPalindrome(words:Array<String>):String {
16+
words.forEach { word->
17+
var l=0
18+
var r= word.lastIndex
19+
while (word[l]== word[r]) {
20+
if (l>= r)return word
21+
l++
22+
r--
23+
}
24+
}
25+
26+
return""
27+
}
28+
}
29+
30+
// For every word, check that its reverse equals it but using two pointers with slightly different logic
31+
classSolution {
32+
funfirstPalindrome(words:Array<String>):String {
33+
words.forEach { w->
34+
var l=0
35+
var r= w.lastIndex
36+
while (l< r&& w[l]== w[r]) {
37+
l++
38+
r--
39+
}
40+
41+
if (w.length%2==1&& l== r|| l== r+1)return w
42+
}
43+
44+
return""
45+
}
46+
}
47+
48+
// Use Kotlins power to condense the solution
49+
classSolution {
50+
funfirstPalindrome(words:Array<String>)= words
51+
.firstOrNull { it== it.reversed() }?:""
52+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp