码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Longest Common Prefix 解题报告

时间:2014-12-21 20:35:48      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

Longest Common Prefix

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

Show Tags
技术分享

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

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/LongestCommonPrefix_1221_2014.java

LeetCode: Longest Common Prefix 解题报告

标签:

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4176905.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!