Skip to content

Commit 76c45e9

Browse files
committed
add 0014
1 parent 5c2be3a commit 76c45e9

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
| [8](./algorithms/0008) | [8. 字符串转换整数 (atoi)](https://leetcode-cn.com/problems/string-to-integer-atoi/) | [Go](./algorithms/0008/main.go) | 中等 |
1515
| [9](./algorithms/0009) | [9. 回文数](https://leetcode-cn.com/problems/palindrome-number/) | [Go](./algorithms/0009/main.go) | 简单 |
1616
| [11](./algorithms/0011) | [11. 盛最多水的容器](https://leetcode-cn.com/problems/container-with-most-water/) | [Go](./algorithms/0011/main.go) | 中等 |
17+
| [14](./algorithms/0014) | [14. 最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/) | [Go](./algorithms/0014/main.go) | 简单 |
1718
| [79](./algorithms/0079) | [79. 单词搜索](https://leetcode-cn.com/problems/word-search/) | [Go](./algorithms/0079/main.go) | 中等 |
1819

1920

algorithms/0014/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#### [14. 最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/)
2+
3+
难度简单
4+
5+
编写一个函数来查找字符串数组中的最长公共前缀。
6+
7+
如果不存在公共前缀,返回空字符串 `""`
8+
9+
10+
11+
**示例 1:**
12+
13+
```
14+
输入:strs = ["flower","flow","flight"]
15+
输出:"fl"
16+
```
17+
18+
**示例 2:**
19+
20+
```
21+
输入:strs = ["dog","racecar","car"]
22+
输出:""
23+
解释:输入不存在公共前缀。
24+
```
25+
26+
27+
28+
**提示:**
29+
30+
- `0 <= strs.length <= 200`
31+
- `0 <= strs[i].length <= 200`
32+
- `strs[i]` 仅由小写英文字母组成

algorithms/0014/main.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package _0014
2+
3+
func longestCommonPrefix(strs []string) string {
4+
if len(strs) == 0 {
5+
return ""
6+
}
7+
if len(strs) == 1 {
8+
return strs[0]
9+
}
10+
common := ""
11+
for i := 0; i < len(strs[0]); i++ {
12+
c := strs[0][i]
13+
equal := true
14+
for j := 1; j < len(strs); j++ {
15+
if i > len(strs[j])-1 {
16+
return common
17+
}
18+
if strs[j][i] != c {
19+
equal = false
20+
return common
21+
}
22+
}
23+
if equal {
24+
common += string(c)
25+
}
26+
}
27+
return common
28+
}

0 commit comments

Comments
 (0)