Greatest Common Divisor of Strings - LeetCode
Can you solve this real interview question? Greatest Common Divisor of Strings - For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return t
leetcode.com
아이디어
t를 s로 나눌 수 있다고 했고, t와 s 둘 다 나누어져야 하기 때문에 나눌 문자열을 t의 처음부터 i번째까지 반복문을 돌며 찾았다.
또한 둘 다 나눠지는지 확인하기 위해서 split으로 쪼개준 뒤 값이 있는 원소만 리스트에 받았다. (만약 둘 다 나눠진다면 리스트에 값이 없어야 한다.)
내 코드
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
res = ""
for i in range(1, len(str2)+1):
tmp_str1 = [ x for x in str1.split(str2[:i]) if x]
tmp_str2 = [ x for x in str2.split(str2[:i]) if x]
if len(tmp_str1) == 0 and len(tmp_str2) == 0 :
res = str2[:i]
return res
'Coding Test > Python' 카테고리의 다른 글
[백준] 14891번: 톱니바퀴 (골드5, 파이썬) (1) | 2023.12.30 |
---|---|
[백준] 14890번: 경사로 (골드3, 파이썬) (0) | 2023.12.30 |
[LeetCode 75] 1768. Merge Strings Alternately (easy, python) (0) | 2023.12.30 |
[백준] 14888번: 연산자 끼워넣기(실버 1, 파이썬) (0) | 2023.12.29 |
[백준] 14503번: 로봇 청소기 (골드 5, 파이썬) (1) | 2023.12.29 |
Greatest Common Divisor of Strings - LeetCode
Can you solve this real interview question? Greatest Common Divisor of Strings - For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return t
leetcode.com
아이디어
t를 s로 나눌 수 있다고 했고, t와 s 둘 다 나누어져야 하기 때문에 나눌 문자열을 t의 처음부터 i번째까지 반복문을 돌며 찾았다.
또한 둘 다 나눠지는지 확인하기 위해서 split으로 쪼개준 뒤 값이 있는 원소만 리스트에 받았다. (만약 둘 다 나눠진다면 리스트에 값이 없어야 한다.)
내 코드
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
res = ""
for i in range(1, len(str2)+1):
tmp_str1 = [ x for x in str1.split(str2[:i]) if x]
tmp_str2 = [ x for x in str2.split(str2[:i]) if x]
if len(tmp_str1) == 0 and len(tmp_str2) == 0 :
res = str2[:i]
return res
'Coding Test > Python' 카테고리의 다른 글
[백준] 14891번: 톱니바퀴 (골드5, 파이썬) (1) | 2023.12.30 |
---|---|
[백준] 14890번: 경사로 (골드3, 파이썬) (0) | 2023.12.30 |
[LeetCode 75] 1768. Merge Strings Alternately (easy, python) (0) | 2023.12.30 |
[백준] 14888번: 연산자 끼워넣기(실버 1, 파이썬) (0) | 2023.12.29 |
[백준] 14503번: 로봇 청소기 (골드 5, 파이썬) (1) | 2023.12.29 |