Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6bce0ec

Browse files
🐱(string): 1071. 字符串的最大公因子
1 parent 81c5068 commit 6bce0ec

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

‎docs/data-structure/array/README.md‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2708,4 +2708,33 @@ class Solution:
27082708
# print(i, j)
27092709
# 处理特殊情况:[1,-1,1,-1]
27102710
return res and j - i > 1
2711-
```
2711+
```
2712+
2713+
## 1071. 字符串的最大公因子
2714+
2715+
[原题链接](https://leetcode-cn.com/problems/greatest-common-divisor-of-strings/)
2716+
2717+
### 暴力枚举
2718+
2719+
最大公因子必定是 `str1``str2` 的前缀,因此枚举前缀的长度并截取前缀进行匹配即可。
2720+
2721+
```python
2722+
class Solution:
2723+
def gcdOfStrings(self, str1: str, str2: str) -> str:
2724+
length1 = len(str1)
2725+
length2 = len(str2)
2726+
for i in range(min(length1, length2), 0, -1):
2727+
# 枚举
2728+
if length1 % i == 0 and length2 % i == 0:
2729+
# 是否可构成前缀
2730+
if str1[:i] * (length1 // i) == str1 and str1[:i] * (length2 // i) == str2:
2731+
return str1[:i]
2732+
return ''
2733+
```
2734+
2735+
- 时间复杂度:
2736+
- 空间复杂度:
2737+
2738+
### 数学法
2739+
2740+
若存在 `X`,那么有 `str1 + str2 = str2 + str1`

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /