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) {
        
        String res = "";
        
        if(strs.length==0) return res;
        
        Arrays.sort(strs);
        String b = strs[0];
        String e = strs[strs.length-1];
        
        
        for(int i=0;i<b.length();i++)
        {
            char c = b.charAt(i);
            
            if(i>=e.length()||e.charAt(i)!=b.charAt(i))
                    return res;
            res += c;
        }
        return res;
    }
}

 

posted @ 2020-03-19 16:52  好麻烦快点  阅读(90)  评论(0编辑  收藏  举报