forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.kt
80 lines (70 loc) · 2.41 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.igorwojda.string.ispalindrome.tolerant
// iterative solution
private object Solution1 {
private fun isTolerantPalindrome(str: String): Boolean {
var characterRemoved = false
str.forEachIndexed { index, c ->
var lastIndex = str.lastIndex - index
if (characterRemoved) {
lastIndex--
}
if (index >= lastIndex) {
return true
}
if (c != str[lastIndex]) {
if (characterRemoved) {
return false
} else {
characterRemoved = true
}
}
}
return false
}
}
// recursive solution
private object Solution2 {
private fun isTolerantPalindrome(str: String, characterRemoved: Boolean = false): Boolean {
return if (str.isEmpty() || str.length == 1) {
true
} else {
if (str.first() == str.last()) {
isTolerantPalindrome(
str.substring(1 until str.lastIndex),
characterRemoved
)
} else {
if (characterRemoved) {
false
} else {
if (str.length == 2) {
return true
}
println(str)
val removeLeftResult = isTolerantPalindrome(
str.substring(2 until str.lastIndex),
true
)
val removeRightResult = isTolerantPalindrome(
str.substring(1 until str.lastIndex - 1),
true
)
return removeLeftResult || removeRightResult
}
}
}
}
}
// recursive solution 2
private object Solution3 {
private fun isTolerantPalindrome(str: String, characterRemoved: Boolean = false): Boolean {
val revStr = str.reversed()
if (revStr == str) return true
if (characterRemoved) return false
// Remove a single non matching character and re-compare
val removeIndex = str.commonPrefixWith(revStr).length
if (removeIndex + 1 > str.length) return false // reached end of string
val reducedStr = str.removeRange(removeIndex, removeIndex + 1)
return isTolerantPalindrome(reducedStr, true)
}
}