-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0647-palindromic-substrings.kt
71 lines (63 loc) · 1.51 KB
/
0647-palindromic-substrings.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
/*
* Two pointer with outwards extension solution, time O(N^2) and space O(1)
*/
class Solution {
fun countSubstrings(s: String): Int {
var res = 0
for(i in s.indices) {
var l = i
var r = i
while(l >= 0 && r < s.length && s[l] == s[r]) {
res++
l--
r++
}
l = i
r = i+1
while(l >= 0 && r < s.length && s[l] == s[r]) {
res++
l--
r++
}
}
return res
}
}
/*
* Two pointer with outwards extension solution, but with helper function. time O(N^2) and space O(1)
*/
class Solution {
fun countSubstrings(s: String): Int {
var res = 0
fun extend(_l: Int, _r: Int) {
var l = _l
var r = _r
while(l >= 0 && r < s.length && s[l] == s[r]) {
res++
l--
r++
}
}
for(i in s.indices) {
extend(i,i)
extend(i,i+1)
}
return res
}
}
/*
* DP solution, time O(N^2) and space O(N^2)
*/
class Solution {
fun countSubstrings(s: String): Int {
var res = 0
val dp = Array(s.length){ BooleanArray(s.length) }
for(i in s.lastIndex downTo 0) {
for(j in i..s.lastIndex) {
dp[i][j] = s[i] == s[j] && (j-i+1 < 3 || dp[i+1][j-1])
if(dp[i][j]) res++
}
}
return res
}
}