zoukankan      html  css  js  c++  java
  • 14. Longest Common Prefix

    package LeetCode_14
    
    /**
     * 14. Longest Common Prefix
     * https://leetcode.com/problems/longest-common-prefix/
     *
     * Write a function to find the longest common prefix string amongst an array of strings.
    If there is no common prefix, return an empty string "".
    
    Example 1:
    Input: strs = ["flower","flow","flight"]
    Output: "fl"
    
    Example 2:
    Input: strs = ["dog","racecar","car"]
    Output: ""
    Explanation: There is no common prefix among the input strings.
    
    Constraints:
    1. 0 <= strs.length <= 200
    2. 0 <= strs[i].length <= 200
    3. strs[i] consists of only lower-case English letters
     * */
    class Solution {
        /*
        * solution: scanning array, Time:O(s), s is the sum of all characters in all string; Space:O(1)
        * */
        fun longestCommonPrefix(strs: Array<String>): String {
            if (strs == null || strs.isEmpty()) {
                return ""
            }
            var first = strs[0]
            val n = strs.size
            for (i in 1 until n) {
                /*
                * if current word is not startWith first, remove the last letter in first to check again
                * for example first is flower then:
                * flowe, flow, flo, fl
                * */
                while (!strs[i].startsWith(first)) {
                    first = first.substring(0, first.length - 1)
                }
            }
            return first
        }
    }
  • 相关阅读:
    Xcode-调试断点不能停在代码区终极解决方案
    iOS-修改Status Bar
    iOS-appStore发布流程
    iOS-Debug调试
    iOS-项目搭建
    iOS-UIButton-设置button标题和图片位置
    iOS-布局-Masonry-优先级
    intent 传参数
    五大布局
    execute、executeQuery和executeUpdate之间的区别
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13861025.html
Copyright © 2011-2022 走看看