File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ # Dynamic programming
12class Solution :
23 def countSubstrings (self , s : str ) -> int :
34 n = len (s )
@@ -28,3 +29,32 @@ def countSubstrings(self, s: str) -> int:
2829# ๊ณต๊ฐ ๋ณต์ก๋:
2930# - DP ํ
์ด๋ธ(dp)์ O(n^2)์ ๊ณต๊ฐ์ ์ฌ์ฉ
3031# - ์ถ๊ฐ ๋ณ์๋ O(1)์ด๋ฏ๋ก ์ ์ฒด ๊ณต๊ฐ ๋ณต์ก๋๋ O(n^2)
32+
33+
34+ # ํฌ ํฌ์ธํฐ ๋ฐฉ์
35+ class Solution :
36+ def countSubstrings (self , s : str ) -> int :
37+ def expand_around_center (left : int , right : int ) -> int :
38+ count = 0
39+ # ์ข์ฐ๋ก ํ์ฅํ๋ฉฐ ํฐ๋ฆฐ๋๋กฌ์ธ์ง ํ์ธ
40+ while left >= 0 and right < len (s ) and s [left ] == s [right ]:
41+ count += 1
42+ left -= 1
43+ right += 1
44+ return count
45+
46+ total_count = 0
47+ for i in range (len (s )):
48+ # ํ์ ๊ธธ์ด ํฐ๋ฆฐ๋๋กฌ (์ค์ฌ์ด ๋ฌธ์ ํ๋)
49+ total_count += expand_around_center (i , i )
50+ # ์ง์ ๊ธธ์ด ํฐ๋ฆฐ๋๋กฌ (์ค์ฌ์ด ๋ฌธ์ ๋ ๊ฐ)
51+ total_count += expand_around_center (i , i + 1 )
52+
53+ return total_count
54+
55+ # ์๊ฐ ๋ณต์ก๋:
56+ # - ๊ฐ ๋ฌธ์์์ ์ค์ฌ์ ๊ธฐ์ค์ผ๋ก ํ์ฅํ๋ฏ๋ก ์ต๋ O(n) ํ์ฅ
57+ # - ๋ชจ๋ ๋ฌธ์์ ๋ํด ํ์ฅ์ ์๋ํ๋ฏ๋ก O(n^2)
58+
59+ # ๊ณต๊ฐ ๋ณต์ก๋:
60+ # - ์ถ๊ฐ ๊ณต๊ฐ ์ฌ์ฉ ์์ด O(1)
You canโt perform that action at this time.
0 commit comments