-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
848dc5d
commit 138e4c5
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |