-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.longest-common-prefix.js
102 lines (46 loc) · 1.19 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* @lc app=leetcode id=14 lang=javascript
*
* [14] Longest Common Prefix
*/
// @lc code=start
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
return strs.reduce((prev, curr)=>{
let str = ""
for(let i = 0; i<curr.length; i++){
if(curr[i] === prev[i]) str += curr[i]
else break;
}
return str;
})
};
const strs = ["flower","flow","flight"]
longestCommonPrefix(strs);
// @lc code=end
/*
if (strs === undefined || strs.length === 0) { return ''; }
return strs.reduce((prev, next) => {
let i = 0;
while (prev[i] && next[i] && prev[i] === next[i]) i++;
return prev.slice(0, i);
});
*/
/*
let output = strs[0];
for(let i = 1; i<strs.length; i++){
let temp = ""
for(let j = 0; j<strs[i].length; j++){
if(output[j] !== strs[i][j]){
break;
}else{
temp += strs[i][j]
}
}
output = temp;
}
return output;
*/