码迷,mamicode.com
首页 > 编程语言 > 详细

【LeetCode算法】Longest Common Prefix

时间:2018-05-19 17:02:12      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:int   数组   bst   amp   HERE   ==   nat   mon   result   

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就算超过字符串的长度也没关系,所以不用担心数组越界问题

【LeetCode算法】Longest Common Prefix

标签:int   数组   bst   amp   HERE   ==   nat   mon   result   

原文地址:https://www.cnblogs.com/anni-qianqian/p/9060528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!