Coding Test/Python

[LeetCode 75] 1071. Greatest Common Divisor of Strings (easy, python)

lim.dev 2023. 12. 30. 03:31

https://leetcode.com/problems/greatest-common-divisor-of-strings/description/?envType=study-plan-v2&envId=leetcode-75

 

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