|
| 1 | +''' |
| 2 | +๋ฌธ์ ํต์ฌ : palindrome์ธ ๋ถ๋ถ ๋ฌธ์์ด์ ๊ฐ์๋ฅผ ์ธ๋ ๊ฒ์ |
| 3 | +ํด๊ฒฐ๋ฐฉ๋ฒ : |
| 4 | +1) ๋ฌธ์์ด์ ๊ฐ ์์น๋ฅผ palindrome ์ค์ฌ์ผ๋ก ์๊ฐํจ |
| 5 | +2) ์ค์ฌ์์ ์์ชฝ์ผ๋ก ํ์ฅํ๋ฉด์ palindrome ์ธ์ง ํ์ธ |
| 6 | +3) ํ์ ๊ธธ์ด palindrome (์ค์ฌ์ด ํ ๊ธ์)๊ณผ ์ง์ ๊ธธ์ด palindrome (์ค์ฌ์ด ๋ ๊ธ์ ์ฌ์ด) ๋ชจ๋ ํ์ธ |
| 7 | +
|
| 8 | +์๊ฐ ๋ณต์ก๋: O(nยฒ) |
| 9 | + ์ธ๋ถ ๋ฐ๋ณต๋ฌธ์ด n๋ฒ ์คํ๋จ (n์ ๋ฌธ์์ด ๊ธธ์ด) |
| 10 | + ๊ฐ ์ค์ฌ์์ ์ต์
์ ๊ฒฝ์ฐ n๋ฒ๊น์ง ํ์ฅํ ์ ์์ |
| 11 | + ๋ฐ๋ผ์ ์ด ์๊ฐ ๋ณต์ก๋๋ O(n ร n) = O(nยฒ)์ |
| 12 | +
|
| 13 | +๊ณต๊ฐ ๋ณต์ก๋: O(1) |
| 14 | + ์ถ๊ฐ๋ก ์ฌ์ฉํ๋ ๋ฉ๋ชจ๋ฆฌ๋ ๋ช ๊ฐ์ ๋ณ์(count, left, right, palindrome_count)๋ฟ์ |
| 15 | + ์
๋ ฅ ํฌ๊ธฐ์ ๊ด๊ณ์์ด ์ผ์ ํ ๋ฉ๋ชจ๋ฆฌ๋ง ์ฌ์ฉํ๋ฏ๋ก O(1)์ |
| 16 | +''' |
| 17 | + |
| 18 | +class Solution: |
| 19 | + def countSubstrings(self, s: str): |
| 20 | + count = 0 # ์ ์ฒด ํ๋ฌธ ๊ฐ์๋ฅผ ์ ์ฅํ ๋ณ์๋ฅผ 0์ผ๋ก ์ด๊ธฐํ |
| 21 | + |
| 22 | + for i in range(len(s)): # ๋ฌธ์์ด์ ๊ฐ ์ธ๋ฑ์ค๋ฅผ ์ํ |
| 23 | + # i๋ฒ์งธ ๋ฌธ์๋ฅผ ์ค์ฌ์ผ๋ก ํ๋ ํ์ ๊ธธ์ด ํ๋ฌธ๋ค์ ์ฐพ์์ ๊ฐ์๋ฅผ ๋ํจ |
| 24 | + count += self.expandAroundCenter(s, i, i) |
| 25 | + # i์ i+1 ์ฌ์ด๋ฅผ ์ค์ฌ์ผ๋ก ํ๋ ์ง์ ๊ธธ์ด ํ๋ฌธ๋ค์ ์ฐพ์์ ๊ฐ์๋ฅผ ๋ํจ |
| 26 | + count += self.expandAroundCenter(s, i, i + 1) |
| 27 | + |
| 28 | + return count # ์ด ํ๋ฌธ ๊ฐ์ ๋ฐํ |
| 29 | + |
| 30 | + def expandAroundCenter(self, s: str, left: int, right: int) -> int: |
| 31 | + palindrome_count = 0 # ์ด ์ค์ฌ์์ ์ฐพ์ ํ๋ฌธ ๊ฐ์๋ฅผ 0์ผ๋ก ์ด๊ธฐํ |
| 32 | + |
| 33 | + # ์กฐ๊ฑด: ์ผ์ชฝ ์ธ๋ฑ์ค๊ฐ 0 ์ด์์ด๊ณ , ์ค๋ฅธ์ชฝ ์ธ๋ฑ์ค๊ฐ ๋ฌธ์์ด ๊ธธ์ด ๋ฏธ๋ง์ด๊ณ , |
| 34 | + # ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ๋ฌธ์๊ฐ ๊ฐ์ ๋ |
| 35 | + while left >= 0 and right < len(s) and s[left] == s[right]: |
| 36 | + palindrome_count += 1 # ํ๋ฌธ์ ํ๋ ์ฐพ์์ผ๋ฏ๋ก ๊ฐ์ ์ฆ๊ฐ |
| 37 | + left -= 1 # ๋ค์ ํ์ฅ์ ์ํด ์ผ์ชฝ ์ธ๋ฑ์ค๋ฅผ 1 ๊ฐ์ |
| 38 | + right += 1 # ๋ค์ ํ์ฅ์ ์ํด ์ค๋ฅธ์ชฝ ์ธ๋ฑ์ค๋ฅผ 1 ์ฆ๊ฐ |
| 39 | + |
| 40 | + return palindrome_count # ์ด ์ค์ฌ์์ ์ฐพ์ ์ด ํ๋ฌธ ๊ฐ์ ๋ฐํ |
| 41 | + |
| 42 | + |
| 43 | + |
0 commit comments