-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14_Longest Common Prefix.js
46 lines (36 loc) · 1.04 KB
/
14_Longest Common Prefix.js
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
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
let prefix = "";
loop:
for (let i = 1; i <= strs[0].length; i++) {
var sub_str = strs[0].substring(0, i);
for (let j = 1; j < strs.length; j++) {
if (strs[j].indexOf(sub_str) != 0) {
break loop;
}
}
prefix = sub_str;
}
return prefix;
// ======================== Other Solutions ========================
// let prefix = "";
// strs.sort();
// let first = strs[0];
// let last = strs[strs.length - 1];
// let min_length = first.length > last.length ? last.length : first.length
// for (let i = 0; i < min_length; i++) {
// if (first.charAt(i) != last.charAt(i)) {
// console.log("true")
// return prefix;
// }
// prefix += first.charAt(i)
// }
// return prefix;
};
// var strs = ["flower", "flow", "flight"]
var strs = ["a"]
var result = longestCommonPrefix(strs);
console.log(result);