DEV Community

duccanhole
duccanhole

Posted on

code every day with me

--DAY 4--
Hi, I am going to make #100DaysOfCode Challenge.Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:
-Problem: Longest Common Prefix
-Detail: https://leetcode.com/problems/longest-common-prefix/
-My solution (javascript):

var longestCommonPrefix = function(str) {
    if(str.length==0) return '';
    let prefix='';
    for(let i=0;i<str[0].length;i++){
        let check=true;
        for(let j=1;j<str.length;j++){
            if(str[j].charAt(i)!=str[0].charAt(i)){
                return prefix;
            }
        }
        if(check) prefix+=str[0].charAt(i);
    }
    return prefix;
};
Enter fullscreen mode Exit fullscreen mode

-->If you have better solution or any question, please comment below. I will appreciate.

Top comments (0)