[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.

解法一

思路

暴力解法,直接双重循环,其中i指向strs[0]中的各个字母,j指向strs数组中的各个字符串,将strs[0]中的各个字母分别与j所指字符串的对应位置的字母进行对比,如果遇到不相等的字母,则直接返回commonPre。由于各个字符串的长度不相等,如果strs[0]是最短的字符串,那么循环过程中不会遇到问题。如果strs[0]较长,而与之对比的字符串比较短,那么当扫描到较短字符串的最后一个字母时,也直接结束扫描。

代码

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0 ||strs == null) return "";
        String commonPre = "";
        for(int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            for(int j = 1; j < strs.length; j++) {
                if(strs[j].length() <= i || strs[j].charAt(i)!=c)
                    return commonPre;
            }
            commonPre += Character.toString(c);
        }
        return commonPre;
    }
}

解法二

思路

先找出第一个字符串和第二个字符串的最长公共前缀pre,然后再找pre和第三个字符串的最长公共前缀,找到后更新pre,依次类推。
怎么找两个字符串的最长公共前缀呢?可以用一个循环,先默认字符串1是字符串1和字符串2的最长公共前缀,然用startsWith方法来判断,如果不是,则取字符串1的substring(0, length()-1)继续判断,直到找出两个字符串的最长公共前缀,循环结束。

代码

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

解法三

思路

我们再来看一种解法,这种方法给输入字符串数组排了个序,想想这样做有什么好处?既然是按字母顺序排序的话,那么有共同字母多的两个字符串会被排到一起,而跟大家相同的字母越少的字符串会被挤到首尾两端,那么如果有共同前缀的话,一定会出现在首尾两端的字符串中,所以我们只需要找首尾字母串的共同前缀即可。比如例子1排序后为 ["flight", "flow", "flower"],例子2排序后为 ["cat", "dog", "racecar"],虽然例子2没有共同前缀,但也可以认为共同前缀是空串,且出现在首尾两端的字符串中。由于是按字母顺序排的,而不是按长度,所以首尾字母的长度关系不知道,为了防止溢出错误,我们只遍历而这种较短的那个的长度,找出共同前缀返回即可。

代码

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0 ||strs == null) return "";
        Arrays.sort(strs);
        int len = Math.min(strs[0].length(),strs[strs.length-1].length());
        int i = 0;
        while(i < len && strs[0].charAt(i) == strs[strs.length-1].charAt(i))
            i++;
        return strs[0].substring(0, i);
    }
}

关于String的总结

==null 和 ==""

这两个不是一回事,null指的是一个String类的对象没有指向任何东西,而""指的是String类的对象指向了一个空串。

length和length()

length是属性,是针对数组说的,length()是方法,是String类的一个方法。

String类的常用方法

Java-String类的常用方法总结

posted @ 2018-09-28 15:59  shinjia  阅读(319)  评论(0编辑  收藏  举报