果果1020

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

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         if (strs == null || strs.length == 0) {
 4             return "";
 5         } else if (strs.length < 2) {
 6             return strs[0];
 7         }
 8 
 9         String r = strs[0];
10         int index = r.length();
11         for (int i = 1; i < strs.length; i++) {
12             int j = 0;
13             for (; j < strs[i].length() && j < index; j++) {
14                 if (strs[i].charAt(j) != r.charAt(j)) {
15                     break;
16                 }
17             }
18             if (j == 0) {
19                 return "";
20             }
21             index = j;
22         }
23 
24         return r.substring(0, index);
25     }
26 }

 

posted on 2017-01-02 18:29  果果1020  阅读(72)  评论(0)    收藏  举报