zoukankan      html  css  js  c++  java
  • 14. Longest Common Prefix 最长的公共字符串开头

    [抄题]:

    Write a function to find the longest common prefix string amongst an array of strings.

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

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

     [暴力解法]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    字符串数组为空、长度为0的情况都需要考虑

    [思维问题]:

    知道要从最短的前缀开始找,还以为要排序

    [一句话思路]:

    每个单词都用.indexof()逐个压缩前缀

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    对前缀字符串进行压缩

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    • int indexOf(String str): 返回指定字符串在字符串中第一次出现处的索引,如果此字符串中没有这样的字符串,则返回 -1。

    若strs[i].indexOf(pre) == 0,则有此前缀。这是判断前缀的新方法。

    [关键模板化代码]:

    每个单词都要做前缀压缩

    for (int i = 1; i < n; i++) {
                while (strs[i].indexOf(pre) != 0) {
                    pre = pre.substring(0, pre.length() - 1);
                }
            }

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    public class Solution {
        /**
         * @param strs: A list of strings
         * @return: The longest common prefix
         */
        public String longestCommonPrefix(String[] strs) {
            //corner case
            if (strs == null) {
                return "";
            }
            if (strs.length == 0) {
                return "";
            }
            //define pre
            String pre = strs[0];
            int n = strs.length;
            //shorten pre
            for (int i = 1; i < n; i++) {
                while (strs[i].indexOf(pre) != 0) {
                    pre = pre.substring(0, pre.length() - 1);
                }
            }
            //return
            return pre;
        }
    }
    View Code
  • 相关阅读:
    BZOJ3585&3339mex——主席树
    BZOJ1926[Sdoi2010]粟粟的书架——二分答案+主席树
    BZOJ2662[BeiJing wc2012]冻结——分层图最短路
    BZOJ1433[ZJOI2009]假期的宿舍——二分图最大匹配
    BZOJ1087[SCOI2005]互不侵犯——状压DP
    BZOJ4808马——二分图最大独立集
    BZOJ3175[Tjoi2013]攻击装置——二分图最大独立集
    BZOJ3524[Poi2014]Couriers——主席树
    BZOJ4010[HNOI2015]菜肴制作——拓扑排序+堆
    BZOJ2588Count on a tree——LCA+主席树
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8597074.html
Copyright © 2011-2022 走看看