-
Notifications
You must be signed in to change notification settings - Fork 1
/
1071.字符串的最大公因子.java
72 lines (69 loc) · 1.41 KB
/
1071.字符串的最大公因子.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* @lc app=leetcode.cn id=1071 lang=java
*
* [1071] 字符串的最大公因子
*
* https://leetcode-cn.com/problems/greatest-common-divisor-of-strings/description/
*
* algorithms
* Easy (49.90%)
* Likes: 77
* Dislikes: 0
* Total Accepted: 11.5K
* Total Submissions: 20.4K
* Testcase Example: '"ABCABC"\n"ABC"'
*
* 对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
*
* 返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
*
*
*
* 示例 1:
*
* 输入:str1 = "ABCABC", str2 = "ABC"
* 输出:"ABC"
*
*
* 示例 2:
*
* 输入:str1 = "ABABAB", str2 = "ABAB"
* 输出:"AB"
*
*
* 示例 3:
*
* 输入:str1 = "LEET", str2 = "CODE"
* 输出:""
*
*
*
*
* 提示:
*
*
* 1 <= str1.length <= 1000
* 1 <= str2.length <= 1000
* str1[i] 和 str2[i] 为大写英文字母
*
*
*/
// @lc code=start
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()));
}
private int gcd(int m, int n) {
int result;
while (n != 0) {
result = m % n;
m = n;
n = result;
}
return m;
}
}
// @lc code=end