Skip to content

Commit

Permalink
Palindromic Substrings
Browse files Browse the repository at this point in the history
  • Loading branch information
forest000014 committed Jan 2, 2025
1 parent 848dc5d commit 138e4c5
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions palindromic-substrings/forest000014.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
time complexity: O(n^2)
space complexity: O(1)
λͺ¨λ“  κ°€λŠ₯ν•œ μ‘°ν•©(O(n^2))에 λŒ€ν•΄ palindrome μ—¬λΆ€λ₯Ό 검사(O(n))ν•˜λŠ” brute forceλŠ” O(n^3).
i번째 λ¬Έμžμ—μ„œ μ‹œμž‘ν•˜μ—¬, μ•ž/λ’€λ‘œ ν•œ κΈ€μžμ”© λŠ˜λ €κ°€λ©΄μ„œ νƒμƒ‰ν•˜λ˜, ν•œλ²ˆμ΄λΌλ„ μ•ž/λ’€ κΈ€μžκ°€ μ„œλ‘œ λ‹€λ₯΄λ‹€λ©΄ κ·Έ μ΄ν›„λŠ” νƒμƒ‰ν•˜μ§€ μ•Šμ„ 수 있음. 이 κ²½μš°λŠ” O(n^2).
*/
class Solution {
public int countSubstrings(String s) {
int ans = 0;
for (int i = 0; i < s.length(); i++) {
int head = i, tail = i;
while (head >= 0 && tail < s.length()) {
if (s.charAt(head) == s.charAt(tail)) {
ans++;
} else {
break;
}
head--;
tail++;
}

head = i;
tail = i + 1;
while (head >= 0 && tail < s.length()) {
if (s.charAt(head) == s.charAt(tail)) {
ans++;
} else {
break;
}
head--;
tail++;
}
}

return ans;
}
}

0 comments on commit 138e4c5

Please sign in to comment.