File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/greatest-common-divisor-of-strings/?envType=problem-list-v2&envId=whcgn2eg
2+
3+ import sys
4+ from collections import defaultdict
5+ from collections import deque
6+
7+ sys .stdin = open ("./input.txt" ,'r' )
8+
9+
10+ class Solution :
11+ def gcdOfStrings (self , str1 : str , str2 : str ) -> str :
12+ #1. 최대공약수 M 구하기
13+ len1 = len (str1 )
14+ len2 = len (str2 )
15+ M = self .GCD (str1 ,str2 )
16+
17+ #2. M의 약수 길이로 str1을 짤라서 str를 만들고, 해당 str을 토대로 만든 문자열이 str1 / str2와 일치하는지 확인
18+ for num in range (M ,0 ,- 1 ):
19+ if (M % num == 0 ):
20+ target = str1 [0 :num ]
21+ mul1 = len1 // num
22+ mul2 = len2 // num
23+
24+ if (str1 == target * mul1 and str2 == target * mul2 ):
25+ return target
26+ return ""
27+
28+
29+ def GCD (self , str1 , str2 ):
30+ N = len (str1 )
31+ M = len (str2 )
32+ min_number = min (N ,M )
33+ for i in range (min_number ,0 ,- 1 ):
34+ if (N % i == 0 and M % i == 0 ):
35+ return i
36+
37+
38+ answer = Solution ()
39+ print (answer .gcdOfStrings (str1 = "ABCABC" , str2 = "ABC" )) # "ABC"
40+
41+ print (answer .gcdOfStrings (str1 = "ABABAB" , str2 = "ABAB" )) # "AB"
42+ print (answer .gcdOfStrings (str1 = "LEET" , str2 = "CODE" )) # ""
43+ print (answer .gcdOfStrings (str1 = "AAAAAB" , str2 = "AAA" )) # ""
You can’t perform that action at this time.
0 commit comments