Write a function to find the longest common prefix string amongst an array of strings.
If There is no common prefix, return an empty string ""
.
Example 1:
Input: ["Flower", "flow", "Flight""FL"
Example 2:
Input: ["dog", "racecar", "Car""" "explanation:there is no common prefix among the input strings.
Note:
All given inputs is in lowercase letters a-z
.
Ideas:
According to the first string, the loop is continually judged after the string
Code:
classSolution { PublicString Longestcommonprefix (string[] strs) {if(NULL= = STRs | | Strs.length = = 0){ return""; }Else if(Strs.length = = 1){ returnStrs[0]; The String result= ""; for(inti = 1;i<=strs[0].length (); i++) {String prefix= strs[0].substring (0, i); for(intj=1;j<strs.length;j++){ if(Strs[j].startswith (prefix)) {if(j==strs.length-1) {result=prefix; } }Else{ Break; } } } returnresult; }}
String.substring (0,x), the second parameter is magical, x even more than the length of the string does not matter, so do not worry about the array out of bounds
"Leetcode algorithm" longest Common Prefix