Skip to content

Commit 4f13e8f

Browse files
committed
add 最长公共前缀
1 parent ef035df commit 4f13e8f

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- [Two Sum](https://github.com/ScoutYin/LeetCode-JavaScript/blob/master/solutions/easy/twoSum.md)
99
- [Search Insert Position](https://github.com/ScoutYin/LeetCode-JavaScript/blob/master/solutions/easy/searchInsert.md)
1010
- [Count And Say](https://github.com/ScoutYin/LeetCode-Javascript/blob/master/solutions/easy/countAndSay.md)
11+
- [最长公共前缀](https://github.com/ScoutYin/LeetCode-Javascript/blob/master/solutions/easy/longestCommonPrefix.md)
1112

1213
### Medium
1314

solutions/easy/longestCommonPrefix.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## 最长公共前缀
2+
3+
> [领扣-最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/description/)
4+
5+
### Question
6+
7+
编写一个函数来查找字符串数组中的最长公共前缀。
8+
9+
如果不存在公共前缀,返回空字符串 ""。
10+
11+
所有输入只包含小写字母 a-z 。
12+
13+
#### Example:
14+
```shell
15+
输入:["flower","flow","flight"]
16+
输出:"fl"
17+
```
18+
19+
```shell
20+
输入: ["dog","racecar","car"]
21+
输出: ""
22+
解释: 输入不存在公共前缀。
23+
```
24+
25+
### Solution
26+
```javascript
27+
/**
28+
* @param {string[]} strs
29+
* @return {string}
30+
*/
31+
const longestCommonPrefix = (strs) => {
32+
if (!strs.length || strs[0] === '') return ''
33+
if (strs.length === 1) return strs[0]
34+
let index = 1
35+
let last = ''
36+
let prefix = ''
37+
const check = () => {
38+
prefix = strs[0].substring(0, index)
39+
if (last === prefix) return
40+
const isCommon = strs.every(str => str.indexOf(prefix) === 0)
41+
if (isCommon) {
42+
last = prefix
43+
index++
44+
check()
45+
}
46+
}
47+
check()
48+
return last
49+
}
50+
```
51+
52+
### 需注意的的几种情况
53+
54+
输入:`[]``[""]``["a"]``["a", "a"]`

0 commit comments

Comments
 (0)