Skip to content

Commit f7f3ee1

Browse files
horizontal approach longest common prefix
1 parent 2f312e7 commit f7f3ee1

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

leetcode/LongestCommonPrefix.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1-
function longestCommonPrefix(strs) {}
1+
function longestCommonPrefix(strs) {
2+
let prefix = strs[0];
3+
for (let i = 0; i < strs.length; i++) {
4+
while (strs[i].indexOf(prefix) != 0) {
5+
prefix = prefix.substring(0, prefix.length - 1);
6+
if (prefix.length === 0) return "";
7+
}
8+
}
9+
return prefix;
10+
}
211

3-
console.log(longestCommonPrefix(["flower", "flower", "flower", "flower"]));
12+
console.log(longestCommonPrefix(["flower", "flow", "flight"]));

0 commit comments

Comments
 (0)