File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ string s가 주어졌을 때, s에서 나올 수 있는 palindrome의 조건을 만족하는 substring 개수를 구하라.
3+ (s는 전부 소문자, 1이상 1000이하)
4+
5+ 1. 완전 탐색
6+ - 나올 수 있는 모든 경우의 수 substring을 만들어 palindrome의 조건을 만족하는지 계산
7+
8+ TC: O(N^3)
9+ SC: O(N)
10+
11+ 2. 최적화 - 중심 확장
12+ - 모든 palindrome은 어떤 중심을 기준으로 좌우 대칭인 원리를 이용
13+ => 문자열의 모든 위치를 중심으로 삼고, 양쪽으로 좌우를 확장하며 검사하면 됨
14+ - 중심 개수: 2n - 1
15+
16+ TC: O(N^2)
17+ SC: O(1)
18+
19+ 3. 최적화 - DP
20+ 1. 길이 1인 문자열은 항상 팰린드롬
21+ dp[i][i] = True
22+ 2. 길이 2인 문자열은 두 문자가 같으면 팰린드롬
23+ s[i] == s[i+1] -> dp[i][i+1] = True
24+ 3. 길이 3 이상인 문자열은 끝 두 문자열이 같고 안에 문자열도 모두 같아야 팰린드롬
25+ s[i] == s[j] and dp[i+1][j-1] == True -> dp[i][j] = True
26+ (dp[i+1][j-1] == True시, s[i+1...j-1] 구간의 문자열이 이미 팰린드롬이라는 뜻)
27+
28+ TC: O(N^2)
29+ SC: O(N^2)
30+ """
31+
32+ class Solution :
33+ def countSubstrings (self , s : str ) -> int :
34+ cnt = 0
35+ n = len (s )
36+ dp = [[False ] * n for _ in range (n )]
37+
38+ # 길이 1 => 항상 팰린드롬
39+ for i in range (n ):
40+ dp [i ][i ] = True
41+ cnt += 1
42+
43+ # 길이 2 => 같은 문자면 팰린드롬
44+ for i in range (n - 1 ):
45+ if s [i ] == s [i + 1 ]: # 서로 같은 문자면
46+ dp [i ][i + 1 ] = True # 팰린드롬
47+ cnt += 1
48+
49+ # 길이 3 이상
50+ for length in range (3 , n + 1 ): # length는 부분 문자열의 길이
51+ for i in range (n - length + 1 ):
52+ j = i + length - 1 # 끝 인덱스
53+ if s [i ] == s [j ] and dp [i + 1 ][j - 1 ]:
54+ dp [i ][j ] = True
55+ cnt += 1
56+
57+ return cnt
You can’t perform that action at this time.
0 commit comments