forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.kt
62 lines (51 loc) · 1.42 KB
/
solution.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.igorwojda.string.ispalindrome.basic
// string reverse
private object Solution1 {
private fun isPalindrome(str: String): Boolean {
return str == str.reversed()
}
}
// iterative, double pointer solution
private object Solution2 {
private fun isPalindrome(str: String): Boolean {
var leftIndex = 0
var rightIndex = str.lastIndex
while (leftIndex <= rightIndex) {
val leftValue = str[leftIndex]
val rightValue = str[rightIndex]
if (leftValue != rightValue) {
return false
}
leftIndex++
rightIndex--
}
return true
}
}
// iterative, double pointer solution
private object Solution3 {
private fun isPalindrome(str: String): Boolean {
str.forEachIndexed { index, char ->
val rightIndex = str.lastIndex - index
if (char != str[rightIndex])
return false
if (index > rightIndex)
return true
}
return true
}
}
// recursive solution
private object Solution4 {
private fun isPalindrome(str: String): Boolean {
return if (str.isEmpty() || str.length == 1) {
true
} else {
if (str.first() == str.last()) {
isPalindrome(str.substring(1 until str.lastIndex))
} else {
false
}
}
}
}