Title: Longest public prefix

Write a function to find the longest public prefix in an array of strings.

Returns the empty string “” if no public prefix exists.

Example:

Example 1:

Input: ["flower","flow","flight"] Output: "fl"Copy the code

Example 2:

Input: ["dog","racecar","car"] Output: "" Explanation: The input does not have a common prefix.Copy the code

Description:

All inputs contain only lowercase letters A-z.

Using the language JavaScript:

/ * * *@param {string[]} strs
 * @return {string}* /
var longestCommonPrefix = function(strs) {

    if(strs[0] = =null) {return "";
    }
    for(var i=0; i<strs[0].length; i++){var re = strs[0].charAt(i);
        for(var j=1; j<strs.length; j++){if(i==strs[j].length || strs[j].charAt(i) ! = re ){return strs[0].substring(0, i); }}}return strs[0];
};
Copy the code

Analysis:

We need to know how to determine the number of characters in a string, so I use the charAt () method, which returns the character at the specified index position. When I need to show what characters from bits to bits of a string are, I use the substring method, which extracts the characters in the string between two specified subscripts.

The first string in the STRS array is checked to see if it is empty. If it is empty, the prefix cannot be the same.

We only need to judge the STRS the first string in the array, using the for loop, the string in each byte value ascribed to re, the additional string after the comparison, if the first string is less than the length of the array, or string behind the position of the character is not fit to return the STRS first before I bit string in the array.