Skip to content

Commit 4ec527e

Browse files
author
Jeongwon Na
committed
solution: palindromic substrings
1 parent cb7b808 commit 4ec527e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

palindromic-substrings/njngwn.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Time Complexity: O(n*n), n: s.length()
2+
// Space Complexity: O(1)
3+
class Solution {
4+
public int countSubstrings(String s) {
5+
int cnt = 0;
6+
7+
for (int i = 0; i < s.length(); i++, cnt++) { // i: center of palindrom
8+
// odd number palindrom: e.g. aba
9+
int left = i-1, right = i+1;
10+
11+
while (left >= 0 && right < s.length()) {
12+
if (s.charAt(left) != s.charAt(right)) {
13+
break;
14+
}
15+
cnt++;
16+
left--;
17+
right++;
18+
}
19+
20+
// even number palindrom: e.g. abba
21+
left = i;
22+
right = i+1;
23+
24+
while (left >= 0 && right < s.length()) {
25+
if (s.charAt(left) != s.charAt(right)) {
26+
break;
27+
}
28+
cnt++;
29+
left--;
30+
right++;
31+
}
32+
}
33+
34+
return cnt;
35+
}
36+
}

0 commit comments

Comments
 (0)