forked from hitesh00025/Algorithms-In-Javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestCommanPrefix.js
More file actions
38 lines (30 loc) · 750 Bytes
/
Copy pathlongestCommanPrefix.js
File metadata and controls
38 lines (30 loc) · 750 Bytes
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
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
var prefix = strs[0];
var newArray=strs[0]?strs[0].split(''):[];
var result;
var pushResult=[];
for( var i=1; i<strs.length; i++)
{
var b = strs[i].split('');
for( var j=0; j< b.length; j++) {
if(newArray[j]===b[j]){
result=result?result+b[j]:b[j];
}
}
if(result)
{
pushResult.push(result);
}
result=undefined;
}
if(pushResult.length ===1){
return pushResult[0];
}
return longestCommonPrefix(pushResult);
};
var data =['flower', 'flow', 'hello', 'floet','flods']
console.log(longestCommonPrefix(data));