首页 > 代码库 > Leetcode-Longest Common Prefix

Leetcode-Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Solution:

 1 public class Solution { 2     public String longestCommonPrefix(String[] strs) { 3         String res = ""; 4         if (strs.length==0) return res; 5         if (strs.length==1) return strs[0]; 6         StringBuilder builder = new StringBuilder(); 7  8         for (int i=0;i<strs[0].length();i++){ 9             char cur = strs[0].charAt(i);10             boolean match = true;11             for (int j=1;j<strs.length;j++)12                 if (i>=strs[j].length() || cur!=strs[j].charAt(i)){13                     match = false;14                     break;15                 }16             if (!match) break;17             else builder.append(cur);18         }19 20         return builder.toString();21     }22 }

 

Leetcode-Longest Common Prefix