14. Longest Common Prefix

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

For instance: ["ab", "bc"] returns ""; ["a", "ab"] returns "a".

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if (strs == null || strs.length == 0) return "";
 4         if (strs.length == 1) return strs[0];
 5         
 6         StringBuilder sb = new StringBuilder();
 7 
 8         for (int j = 0; j < strs[0].length(); j++) {
 9             for (int i = 0; i < strs.length; i++) {
10                 if (strs[i].length() < j + 1 || strs[i].charAt(j) != strs[0].charAt(j)) {
11                     return sb.toString();
12                 }
13             }
14             sb.append(strs[0].charAt(j));
15         }
16         return sb.toString();
17     }
18 }

转载请注明出处。

posted @ 2015-01-06 09:32  北叶青藤  阅读(152)  评论(0)    收藏  举报