LeetCode Longest Common Prefix

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

找出所有字符串的最长公共前缀。

 

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         String string="";
 4         String longest="";
 5         if (strs.length==0) {
 6             return string;
 7         }
 8         for (int i = 1; i <= strs[0].length(); i++) {
 9             string=strs[0].substring(0, i);
10             for (String s : strs) {
11                 if (!s.startsWith(string)) {
12                     return longest;
13                 }
14             }
15             longest=string;
16         }
17         return longest;
18     }
19 }

 

posted @ 2014-10-30 18:35  birdhack  阅读(119)  评论(0编辑  收藏  举报