Skip to content

Commit 7ce69bc

Browse files
committed
feat: add question 14
1 parent 74ae9dc commit 7ce69bc

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

14.data

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
["flower","flow","flight"]
2+
["dog","racecar","car"]

14.最长公共前缀.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* @lc app=leetcode.cn id=14 lang=javascript
3+
*
4+
* [14] 最长公共前缀
5+
*
6+
* 1. 要做判空处理, 直接返回 ''
7+
* 2. 取最短字符串, 最终结果长度肯定 <= 最短长度
8+
* 3. 取当前字符, 和后几个字符串的当前位置字符比较, 如果有不同, 则匹配失败, 直接返回结果
9+
*/
10+
11+
// @lc code=start
12+
/**
13+
* @param {string[]} strs
14+
* @return {string}
15+
*/
16+
var longestCommonPrefix = function(strs) {
17+
if (strs.length === 0) {
18+
return '';
19+
}
20+
21+
var minLength = Math.min(...strs.map(str => str.length));
22+
var result = [];
23+
24+
for (var i = 0; i < minLength; i++) {
25+
var ch = strs[0][i];
26+
27+
for (var j = 1; j < strs.length; j++) {
28+
if (ch !== strs[j][i]) {
29+
return result.join('');
30+
}
31+
}
32+
33+
result.push(ch);
34+
}
35+
36+
return result.join('');
37+
};
38+
// @lc code=end
39+

0 commit comments

Comments
 (0)