Skip to content

Commit 7f7ba65

Browse files
committed
upd: Longest Common Prefix
1 parent 314ee58 commit 7f7ba65

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ LeetCode JavaScript Solution
1919
| Remove Nth Node From End of List | Medium | 2018-03-16 |
2020
| Valid Parentheses | Easy | 2018-03-16 |
2121
| Remove Duplicates from Sorted Array | Easy | 2018-03-16 |
22+
| Longest Common Prefix | Easy | 2018-03-16 |

src/longestCommonPrefix.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
var longestCommonPrefix = function(strs) {
6+
if (!strs.length) return '';
7+
let i = 0;
8+
let ret = '';
9+
while (true) {
10+
let temp = strs[0] && strs[0][i] || '';
11+
let flag = strs.reduce((prev, cur) => {
12+
return prev && cur[i] === temp;
13+
}, true);
14+
if (flag) {
15+
++i;
16+
ret += temp;
17+
} else {
18+
break;
19+
}
20+
}
21+
return ret;
22+
};

0 commit comments

Comments
 (0)