【LeetCode】 1071. Greatest Common Divisor of Strings 字符串的最大公因子(Easy)(JAVA)

【LeetCode】 1071. Greatest Common Divisor of Strings 字符串的最大公因子(Easy)(JAVA)

题目地址: https://leetcode.com/problems/greatest-common-divisor-of-strings/

题目描述:

For strings S and T, we say “T divides S” if and only if S = T + … + T (T concatenated with itself 1 or more times)

Return the largest string X such that X divides str1 and X divides 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: ""

Note:

1. 1 <= str1.length <= 1000
2. 1 <= str2.length <= 1000
3. str1[i] and str2[i] are English uppercase letters.

题目大意

对于字符串 S 和 T,只有在 S = T + … + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。

返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。

解题方法

普通的方法,就是遍历找出公因子

class Solution {
    public String gcdOfStrings(String str1, String str2) {
        if (str1.length() == 0 || str2.length() == 0) return "";
        int start = 0;
        for (; start < str1.length() && start < str2.length(); start++) {
            if (str1.charAt(start) != str2.charAt(start)) break;
        }
        if (start <= 0) return "";
        if (str1.length() < str2.length()) {
            String temp = str1;
            str1 = str2;
            str2 = temp;
        }
        for (int i = start - 1; i >= 0; i--) {
            if (str1.length() % (i + 1) != 0 || str2.length() % (i + 1) != 0 || !str2.equals(str1.substring(0, str2.length()))) continue;
            String temp = str1.substring(0, i + 1);
            int j = 1;
            for (; (j + 1) * (i + 1) <= str1.length() || (j + 1) * (i + 1) <= str2.length(); j++) {
                if ((j + 1) * (i + 1) <= str1.length()) {
                    if (!temp.equals(str1.substring(j * (i + 1), (j + 1) * (i + 1)))) break;
                }

                if ((j + 1) * (i + 1) <= str2.length()) {
                    if (!temp.equals(str2.substring(j * (i + 1), (j + 1) * (i + 1)))) break;
                }
            }

            if ((j + 1) * (i + 1) > str1.length() && (j + 1) * (i + 1) > str2.length()) return temp;
        }
        return "";
    }
}

执行用时 : 4 ms, 在所有 Java 提交中击败了 28.07% 的用户
内存消耗 : 39 MB, 在所有 Java 提交中击败了 8.80% 的用户

一看排名就知道,这种方法太耗时,后面看了大神的做法

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

    public int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}

执行用时 : 1 ms, 在所有 Java 提交中击败了 93.63% 的用户
内存消耗 : 38.4 MB, 在所有 Java 提交中击败了 10.40% 的用户

发布了81 篇原创文章 · 获赞 6 · 访问量 2282

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104811152