首页 > 编程语言 > 详细

「Leetcode」14. Longest Common Prefix(Java)

时间:2019-02-10 10:11:53      阅读:149      评论:0      收藏:0      [点我收藏+]

分析

与其说是算法题,不如说是语言特性题。
这题要是对Java的String相关函数掌握的比较熟练,写起来的速度(各种意义上)就会很快。
大致的思路都是一致的,差不到哪里去,无非是枚举长度。值得一提的是,从长到短的枚举顺序要比从短到长优得多。

代码

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        
        String prefix = strs[0];
        
        for (int i = 1; i < strs.length; ++i) {
            while (!strs[i].startsWith(prefix)) {
                prefix = prefix.substring(0, prefix.length() - 1);
                
                if (prefix.isEmpty()) {
                    break;
                }
            }
        }
        
        return prefix;
    }
}

「Leetcode」14. Longest Common Prefix(Java)

原文:https://www.cnblogs.com/samhx/p/LeetCode-0014.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!