LeetCode: Longest Common Prefix 解题报告

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

2015.1.2 redo:

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         String ret = "";
 4         if (strs == null || strs.length == 0) {
 5             return ret;
 6         }
 7         
 8         int minLen = Integer.MAX_VALUE;
 9         for (String str: strs) {
10             minLen = Math.min(str.length(), minLen);
11         }
12         
13         for (int i = 0; i < minLen; i++) {
14             for (int j = 1; j < strs.length; j++) {
15                 if (strs[0].charAt(i) != strs[j].charAt(i)) {
16                     return strs[0].substring(0, i);
17                 }
18             }
19         }
20         
21         return strs[0].substring(0, minLen);
22     }
23 }
View Code

 

GITHUB:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值