「Leetcode」14. Longest Common Prefix(Java)

分析

与其说是算法题,不如说是语言特性题。
这题要是对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;
    }
}
posted @ 2019-02-10 01:13  ISoLT  阅读(228)  评论(0编辑  收藏  举报