[LeetCode / Easy] 1071. Greatest Common Divisor of Strings (Java)

이하얀·2025년 1월 21일
1

📙 LeetCode

목록 보기
4/13

💬 Info



Problem

For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times).

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.



Example

예시 1

  • Input: str1 = "ABCABC", str2 = "ABC"
  • Output: "ABC"

예시 2

  • Input: str1 = "ABABAB", str2 = "ABAB"
  • Output: "AB"

예시 3

  • Input: str1 = "LEET", str2 = "CODE"
  • Output: ""


Constraints

  • 1 <= str1.length, str2.length <= 1000
  • str1 and str2 consist of English uppercase letters.


문제 이해

  • 최대공약수 개념을 문자열로 적용하면 되는 문제


알고리즘

풀이 시간 : 37분

  • 문자열이 완전히 반복되는 구조인지 확인
    • 추가적인 접두사/접미사 검증까지 같이 해야 startsWith, endsWith 사용 가능
  • 문자열 길이의 GCD 계산
  • GCD 길이만큼의 접두사 반환하여 출력
class Solution {
    public String gcdOfStrings(String str1, String str2) {
        if (!(str1 + str2).equals(str2 + str1)) return "";
        if (!(str1.startsWith(str2) && str1.endsWith(str2)) &&
            !(str2.startsWith(str1) && str2.endsWith(str1))) return "";
        return str2.substring(0, gcd(str1.length(), str2.length()));
    }

    private int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}


결과


profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글