Skip to content

Commit 463a7ad

Browse files
committed
longest common prefix
1 parent 0a0159e commit 463a7ad

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

longestCommonPrefix-2.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
var longestCommonPrefix = function(strs) {
6+
let results = strs.shift();
7+
8+
while (strs.length && results.length) {
9+
let key = strs.shift();
10+
if (key.length < results.length){
11+
results = results.substring(0, key.length);
12+
} else {
13+
key = key.substring(0, results.length)
14+
}
15+
16+
while (results !== key && key.length){
17+
key = key.substring(0, key.length - 1)
18+
results = results.substring(0, key.length);
19+
}
20+
}
21+
22+
return results || "";
23+
}

longestCommonPrefix.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
var longestCommonPrefix = function(strs) {
6+
if (strs.length === 0) return ""
7+
let key = strs.shift().split("")
8+
9+
let results = strs.reduce((acc, i) => {
10+
let chars = i.split("")
11+
12+
if (key.length > chars.length) {
13+
chars.length = key.length
14+
}
15+
for(x = 0; x < chars.length; x++){
16+
if (chars[x] !== key[x]){
17+
acc.length = x
18+
break
19+
}
20+
}
21+
return acc
22+
}, key)
23+
24+
return results.join("")
25+
};

0 commit comments

Comments
 (0)