LeetCode: Longest Common Prefix 解题报告

本文深入探讨了在字符串数组中寻找最长公共前缀的两种高效算法实现,通过详细的代码示例,阐述了如何遍历字符串并比较字符,以确定共同的前缀。文章提供了清晰的边界条件处理思路,避免了常见的错误陷阱。

Longest Common Prefix Total Accepted: 24665 Total Submissions: 92370

My Submissions

Question

 Solution 

 

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

 

Show Tags

 

Have you met this question in a real interview? Yes No

 

Discuss

SOULTION1:

解法就是扫一次。不过各种边界条件很容易出错。

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if (strs == null) {
 4             return null;
 5         }
 6         
 7         if (strs.length == 0 || strs[0].length() == 0) {
 8             return "";
 9         }
10         
11         int len = strs[0].length();
12         int i = 0;
13         for (; i < len; i++) {
14             char c = strs[0].charAt(i);
15             
16             int j = 1;
17             for (; j < strs.length; j++) {
18                 if (strs[j].length() <= i || c != strs[j].charAt(i)) {
19                     break;
20                 }
21             }
22             
23             // there is err.
24             if (j < strs.length) {
25                 break;
26             }
27         }
28         
29         // The char i is invalid. 因为读到i时退出,所以不应包含i本身。
30         return strs[0].substring(0, i);
31     }
32 }
View Code

 

SOULTION2:

感谢大神的灵感http://blog.youkuaiyun.com/fightforyourdream/article/details/14642079

重新改写:

 1 public class Solution {
 2     //http://blog.youkuaiyun.com/fightforyourdream/article/details/14642079
 3     public String longestCommonPrefix(String[] strs) {
 4         if (strs == null) {
 5             return null;
 6         }
 7         
 8         if (strs.length == 0) {
 9             return "";
10         }
11         
12         String s = strs[0];
13         int len = s.length();
14         
15         for (int i = 0; i < len; i++) {
16             char c = s.charAt(i);
17             
18             for (int j = 1; j < strs.length; j++) {
19                 if (strs[j].length() <= i || c != strs[j].charAt(i)) {
20                     // The char i is invalid. 因为读到i时退出,所以不应包含i本身。
21                     return s.substring(0, i);
22                 }
23             }
24         }
25         
26         // Didn't break, the whole String is valid.
27         return s;
28     }
29 }
View Code

 

请Floow主页君的GitHUB: 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值