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

Show Tags
LeetCode: Longest Common Prefix 解题报告

SOLUTION 1:

解法很直观。先找到最小长度,然后逐个字母遍历,同时逐个遍历所有的字符串。注意各种小细节:

1. break的时候,应该返回上一个索引指向的子串。

2. 如果没有break,表示minlen长度的字串就是最大pre.

 1 public class Solution {
 2     //http://blog.csdn.net/fightforyourdream/article/details/14642079
 3     public String longestCommonPrefix(String[] strs) {
 4         if (strs == null || strs.length == 0) {
 5             // bug 2: should not return null.
 6             return "";
 7         }
 8         
 9         // Find out the shortest length.
10         String s0 = strs[0];
11         int len = s0.length();
12         for (String s: strs) {
13             len = Math.min(len, s.length());
14         }
15         
16         // The index of the character which is examing.
17         // Bug 3: 当不会break的时候,结果是错的
18         // Bug 4: forget to add int i = 0;
19         for (int i = 0; i < len; i++) {
20             // Bug 1: forget to write charAt(i);
21             char c = s0.charAt(i);
22             for (int j = 0; j < strs.length; j++) {
23                 if (strs[j].charAt(i) != c) {
24                     // Bug 5: write substring to sbustring
25                     return s0.substring(0, i);
26                 }                
27             }
28         }
29         
30         // Never break, means strs[0].0-len is the solution.
31         return s0.substring(0, len);
32     }
33 }
View Code

相关文章: