zoukankan      html  css  js  c++  java
  • LintCode 78:Longest Common Prefix

     
    public class Solution {
        /**
         * @param strs: A list of strings
         * @return: The longest common prefix
         */
        public String longestCommonPrefix(String[] strs) {
            // write your code here
            if(strs.length == 0){
                return "";
            }
            String prefix = strs[0];
            int i = 0;
            int j = 0;
            for ( i=1;i<strs.length;i++){
                if(strs[i].length() == 0){
                    return "";
                }
                for( j=0;j<prefix.length();j++){
                    if(strs[i].charAt(j) != prefix.charAt(j)){
                        prefix = prefix.substring(0,j);
                    }
                }
            }
            return prefix;
        }
    }

     思路:

      默认数组第一个是prefix,然后循环比较数组中的每一个字符串,直到不相等,返回substring即可,返回的substring一定是最长的公共前缀。

      注:判断数组为空或者数组中有空字符串

    时间复杂度:O(第一个字符串长度^2),java耗时1563 ms。

  • 相关阅读:
    6.20 委托
    6.20 VAR 万能变量
    LINQ查询
    LINQ基本语句
    母版页
    分页+组合查询
    Document
    Select查询语句1
    Cookie对象
    Session对象
  • 原文地址:https://www.cnblogs.com/xieweichong/p/5942580.html
Copyright © 2011-2022 走看看