File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ // For every word, check that its reverse equals it
2
+ class Solution {
3
+ fun firstPalindrome (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
+ class Solution {
15
+ fun firstPalindrome (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
+ class Solution {
32
+ fun firstPalindrome (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
+ class Solution {
50
+ fun firstPalindrome (words : Array <String >) = words
51
+ .firstOrNull { it == it.reversed() } ? : " "
52
+ }
You can’t perform that action at this time.
0 commit comments