面试题:最长公共前缀


难度:中等

给k个字符串,求出他们的最长公共前缀(LCP)

样例

在 "ABCD" "ABEF" 和 "ACEF" 中, LCP 为 "A"

在"ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"

答案:

 1 public class Solution {
 2     
 3     // 1. Method 1, start from the first one, compare prefix with next string, until end;
 4     // 2. Method 2, start from the first char, compare it with all string, and then the second char
 5     // I am using method 1 here
 6     public String longestCommonPrefix(String[] strs) {
 7         if (strs == null || strs.length == 0) {
 8             return "";
 9         }
10         String prefix = strs[0];
11         for(int i = 1; i < strs.length; i++) {
12             int j = 0;
13             while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) {
14                 j++;
15             }
16             if( j == 0) {
17                 return "";
18     }
19             prefix = prefix.substring(0, j);
20         }
21         return prefix;
22     }
23 
24 }

优质内容筛选与推荐>>
1、线程本地变更,即ThreadLocal-->Spring事务管理
2、php laravel-admin 学习1
3、python之局部变量引用赋值前的结果
4、删除oracle中BIN开头的表
5、Vue事件总线(eventBus)$on()会多次触发解决办法


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn