Skip to content

Commit 138e4c5

Browse files
committed
Palindromic Substrings
1 parent 848dc5d commit 138e4c5

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
time complexity: O(n^2)
3+
space complexity: O(1)
4+
5+
λͺ¨λ“  κ°€λŠ₯ν•œ μ‘°ν•©(O(n^2))에 λŒ€ν•΄ palindrome μ—¬λΆ€λ₯Ό 검사(O(n))ν•˜λŠ” brute forceλŠ” O(n^3).
6+
i번째 λ¬Έμžμ—μ„œ μ‹œμž‘ν•˜μ—¬, μ•ž/λ’€λ‘œ ν•œ κΈ€μžμ”© λŠ˜λ €κ°€λ©΄μ„œ νƒμƒ‰ν•˜λ˜, ν•œλ²ˆμ΄λΌλ„ μ•ž/λ’€ κΈ€μžκ°€ μ„œλ‘œ λ‹€λ₯΄λ‹€λ©΄ κ·Έ μ΄ν›„λŠ” νƒμƒ‰ν•˜μ§€ μ•Šμ„ 수 있음. 이 κ²½μš°λŠ” O(n^2).
7+
*/
8+
class Solution {
9+
public int countSubstrings(String s) {
10+
int ans = 0;
11+
for (int i = 0; i < s.length(); i++) {
12+
int head = i, tail = i;
13+
while (head >= 0 && tail < s.length()) {
14+
if (s.charAt(head) == s.charAt(tail)) {
15+
ans++;
16+
} else {
17+
break;
18+
}
19+
head--;
20+
tail++;
21+
}
22+
23+
head = i;
24+
tail = i + 1;
25+
while (head >= 0 && tail < s.length()) {
26+
if (s.charAt(head) == s.charAt(tail)) {
27+
ans++;
28+
} else {
29+
break;
30+
}
31+
head--;
32+
tail++;
33+
}
34+
}
35+
36+
return ans;
37+
}
38+
}

0 commit comments

Comments
Β (0)