leetcode-1071-easy

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 the largest string x such that x divides both str1 and str2.

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:

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

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

思路一:先求两字符串长度的最大公约数,然后依次对比最大公约数长度的子字符串是否与两字符串互相匹配

    public static String gcdOfStrings(String str1, String str2) {
        int gcd = gcd(str1.length(), str2.length());

        for (int i = gcd; i >= 1; i--) {
            String temp = str1.substring(0, i);
            if (tempEquals(temp, str1, str2)) {
                return temp;
            }
        }

        return "";
    }

    private static boolean tempEquals(String temp, String str1, String str2) {
        StringBuilder sb = new StringBuilder();
        while (sb.length() < str1.length()) {
            sb.append(temp);
        }

        if (!sb.toString().equals(str1)) {
            return false;
        }

        sb = new StringBuilder();

        while (sb.length() < str2.length()) {
            sb.append(temp);
        }

        return sb.toString().equals(str2);
    }

    private static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
posted @ 2023-03-11 13:37  iyiluo  阅读(26)  评论(0)    收藏  举报