zoukankan      html  css  js  c++  java
  • 【LeetCode算法-14】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: ["flower","flow","flight"]
    Output: "fl"

    Example 2:

    Input: ["dog","racecar","car"]
    Output: ""
    Explanation: There is no common prefix among the input strings.

    Note:

    All given inputs are in lowercase letters a-z.

    思路:

    根据第一个字符串,不断去循环判断后面的字符串

    代码:

    class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(null == strs || strs.length == 0){
                return "";
            }else if(strs.length == 1){
                return strs[0];
            }
            String result = "";
            for(int i = 1;i<=strs[0].length();i++){
                String prefix = strs[0].substring(0,i);
                for(int j=1;j<strs.length;j++){
                    if(strs[j].startsWith(prefix)){
                        if(j==strs.length-1){
                            result = prefix;
                        }
                    }else{
                        break;
                    }
                }
            }
            return result;
        }
    }

    String.substring(0,x),第二个参数很神奇,x就算超过字符串的长度也没关系,所以不用担心数组越界问题

  • 相关阅读:
    js键盘事件以及键盘事件拦截
    GO-&获取地址与*解引用
    Go-map
    第22课
    第21课
    第20课
    基于spring+quartz的分布式定时任务框架
    DeepLearning (三) 预处理:主成分分析与白化
    白化whitening
    如何使用RestTemplate访问restful服务
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/9060528.html
Copyright © 2011-2022 走看看