Skip to content

Commit 508a638

Browse files
committed
palindromic substrings
1 parent d57871a commit 508a638

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public int countSubstrings(String s) {
3+
int count = 0;
4+
int n = s.length();
5+
6+
for (int center = 0; center < 2 * n - 1; center++) {
7+
int left = center / 2;
8+
int right = left + (center % 2); // 홀/짝 팰린드롬 처리
9+
10+
while (left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
11+
count++;
12+
left--;
13+
right++;
14+
}
15+
}
16+
17+
return count;
18+
}
19+
}
20+
// Time Complexity: O(n^2)
21+
// Space Complexity: O(1)
22+
23+
/*
24+
예시: "abc"
25+
중심이 문자일 때:
26+
a (index 0),
27+
b (index 1),
28+
c (index 2)
29+
중심이 문자 사이일 때:
30+
between a and b
31+
between b and c
32+
→ 총 2 * 3 - 1 = 5개의 중심
33+
*/
34+

0 commit comments

Comments
 (0)