最长公共前缀
Category | Difficulty | Likes | Dislikes |
---|---|---|---|
algorithms | Easy (42.32%) | 2227 | - |
Tags
Companies
yelp
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
1
2
2
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
1
2
3
2
3
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
Discussion (opens new window) | Solution (opens new window)
/*
* @Author: 仲灏<izhaong@outlook.com>🌶🌶🌶
* @Date: 2022-05-07 11:35:19
* @LastEditTime: 2022-05-07 12:30:06
* @LastEditors: 仲灏<izhaong@outlook.com>🌶🌶🌶
* @Description: 暂无
* @FilePath: /question100/Users/izhaong/Documents/leetcode/14.最长公共前缀.js
*/
/*
* @lc app=leetcode.cn id=14 lang=javascript
*
* [14] 最长公共前缀
*
* https://leetcode-cn.com/problems/longest-common-prefix/description/
*
* algorithms
* Easy (42.32%)
* Likes: 2227
* Dislikes: 0
* Total Accepted: 822.7K
* Total Submissions: 1.9M
* Testcase Example: '["flower","flow","flight"]'
*
* 编写一个函数来查找字符串数组中的最长公共前缀。
*
* 如果不存在公共前缀,返回空字符串 ""。
*
*
*
* 示例 1:
*
*
* 输入:strs = ["flower","flow","flight"]
* 输出:"fl"
*
*
* 示例 2:
*
*
* 输入:strs = ["dog","racecar","car"]
* 输出:""
* 解释:输入不存在公共前缀。
*
*
*
* 提示:
*
*
* 1 <= strs.length <= 200
* 0 <= strs[i].length <= 200
* strs[i] 仅由小写英文字母组成
*
*
*/
// @lc code=start
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
let prefix = "";
for (let i = 0; i < strs[0].length; i++) {
let rec = strs[0].slice(0, i + 1);
let isStart = false;
for (let j = 0; j < strs.length; j++) {
isStart = false;
const e = strs[j];
if (e.startsWith(rec)) {
isStart = true;
} else {
isStart = false;
break;
}
}
if (isStart) {
prefix = rec;
} else {
break;
}
}
return prefix;
};
// @lc code=end
// @after-stub-for-debug-begin
module.exports = longestCommonPrefix;
// @after-stub-for-debug-end
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
上次更新: 2022/06/05, 20:31:36