[Array / String, Easy] Greatest Common Divisor of Strings

송재호·2025년 3월 9일
0

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

str1과 str2를 정순, 역순으로 합쳤을 때 같지 않으면 substring의 대상이 아님을 알 수 있다.
어떻게 해도 common divisor를 구할 수 없기 때문

되는 케이스에서는 유클리드 호제법을 써서 최대공약수를 구하면 되고
str1또는 str2 아무거나 0부터 substring해서 결과를 리턴하면 된다.

class Solution {
    public String gcdOfStrings(String str1, String str2) {
        if (!(str1 + str2).equals(str2 + str1)) {
            return "";
        }

        int g = gcd(str1.length(), str2.length());
        return str1.substring(0, g);
    }

    private int gcd(int a, int b) {
        while (b != 0) {
            int temp = a % b;
            a = b;
            b = temp;
        }
        return a;
    }
}
profile
식지 않는 감자

0개의 댓글