zoukankan      html  css  js  c++  java
  • 「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;
        }
    }
    
  • 相关阅读:
    【游戏开发】Excel表格批量转换成CSV的小工具
    iOS
    iOS
    Xcode
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
  • 原文地址:https://www.cnblogs.com/samhx/p/LeetCode-0014.html
Copyright © 2011-2022 走看看