[LeetCode] Greatest Common Divisor of Strings

아르당·2026년 3월 30일

LeetCode

목록 보기
231/254
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 문자열 s와 t에 대해, "t는 s를 나눈다"고 하는 것은 s = t + t + t + ... + t + t를 의미한다.
두 문자열 str1과 str2가 주어졌을 때, str1과 str2를 모두 나누는 가장 큰 문자열 x를 반환해라.

Example

#1
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"

#2
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"

#3
Input: str1 = "LEET", str2 = "CODE"
Output: ""

#4
Input: str1 = "AAAAAB", str2 = "AAA"
Output: ""

Constraints

  • 1 <= str1.length, str2.length <= 1000
  • str1과 str2는 영어 대문자로 구성된다.

Solved

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

        int lengthGCD = gcd(str1.length(), str2.length());

        return str1.substring(0, lengthGCD);
    }

    private int gcd(int length1, int length2){
        while(length2 != 0){
            int temp = length1 % length2;
            length1 = length2;
            length2 = temp;
        }

        return length1;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글