Skip to content

Commit c44b9a6

Browse files
committed
fix leetcode 0014 with go
1 parent e4c56f6 commit c44b9a6

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 14. 最长公共前缀
2+
3+
## 链接
4+
https://leetcode-cn.com/problems/longest-common-prefix/
5+
6+
## 难度
7+
简单
8+
9+
## 描述
10+
11+
编写一个函数来查找字符串数组中的最长公共前缀。
12+
13+
如果不存在公共前缀,返回空字符串 ""。
14+
15+
示例 1:
16+
```text
17+
输入: ["flower","flow","flight"]
18+
输出: "fl"
19+
```
20+
示例 2:
21+
```text
22+
输入: ["dog","racecar","car"]
23+
输出: ""
24+
解释: 输入不存在公共前缀。
25+
```
26+
说明:
27+
28+
所有输入只包含小写字母 a-z 。
29+
30+
## 思路
31+
水平扫描,
32+
- 第一个字符串的第一个字节和其余其余字符串的第一个字节比较
33+
- 第一个字符串的第二个字节和其余其余字符串的第二个字节比较
34+
35+
使用 sort.Strings 是按照字符串的字节逐个比较
36+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package _014_Longest_Common_Prefix
2+
3+
import "sort"
4+
5+
func longestCommonPrefix(strs []string) string {
6+
sl := len(strs)
7+
if sl == 0 {
8+
return ""
9+
}
10+
if sl == 1 {
11+
return strs[0]
12+
}
13+
14+
sort.Strings(strs)
15+
16+
lcp := ""
17+
18+
for i, l := 0, len(strs[0]); i < l; i++ {
19+
for si := 1; si < sl; si++ {
20+
if strs[0][i] != strs[si][i] {
21+
return lcp
22+
}
23+
}
24+
lcp += string(strs[0][i])
25+
}
26+
return lcp
27+
}

0 commit comments

Comments
 (0)