# Leetcode 14: Longest Common Prefix longest common prefix

Public number: Write love bug

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

Write a function to find the longest common prefix string array.

If there is no common prefix, it returns 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.

Description:

All input contains only lowercase letters a-z.

Problem-solving ideas Java:

Very simple and very classic a question, I thought at first that the first string group a string to char type. StringBuilder accumulated one by one using the same characters. Because of varying length of the string, you can find the minimum traverse the length of the string, I chose the wrong form of cast, reducing time to traverse.

Code:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int strLen=strs.length;
        if(strLen==0) return "";//空字符串组返回""
        char[] temp=strs[0].toCharArray();
        StringBuilder str = new StringBuilder();
        for (int i=0;i<strs[0].length();i++){//以第一个字符串长度开始比较
            for (int j=1;j<strLen;j++){
                try {
                    if(temp[i]!=strs[j].charAt(i)){
                        return str.toString();
                    }
                }catch (IndexOutOfBoundsException e){//抛出错误,这里错误是指索引超出字符串长度
                    return strs[j];
                }
            }
            str.append(temp[i]);
        }
        return strs[0];
    }
}

There are thought behind Java subString()method, you can specify the length of the string interception, no turn char[]type, but when submitted Leetcode but not as fast operation above this way, this also shows that Java does not support operator overloading, use substring()every time a new character String string, the efficiency is not high.

Finally see a method, the general idea is to find the minimum length of the string, the string interception descending, since used subString()the method, it is better from back to front, because the problem is to find the longest prefix public, descending high efficiency. Specific look:

 public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        int min=Integer.MAX_VALUE;
        String minStr="";
        for(int i=0;i<strs.length;i++){//找出最小长度字符串
            if(min>strs[i].length()){
                minStr=strs[i];
                min=strs[i].length();
            }
        }
        if(min==0) return "";
        for(int i=min;i>=0;i--){//最小长度字符串从长到短截取
            String standard=minStr.substring(0, i);
            int j=0;
            for(j=0;j<strs.length;j++){
                if(strs[j].substring(0, i).equals(standard)) continue;
                else break;
            }
            if(j==strs.length) return standard;
        }
        return "";
    }
}

Original code Link: https://blog.csdn.net/qq_14927217/article/details/72955791

Problem-solving ideas py3:

Opportunistic again, os.path wrapper function commonprefix()in one step.

Code:

class Solution(object):
    def longestCommonPrefix(self, strs):
        import os
        return os.path.commonprefix(strs)

In fact, this function is the use of ASCll code comparing characteristics to write the source code:

def commonprefix(m):
    "Given a list of pathnames, returns the longest common leading component"
    if not m: return ''
    # Some people pass in a list of pathname parts to operate in an OS-agnostic
    # fashion; don't try to translate in that case as that's an abuse of the
    # API and they are already doing what they need to be OS-agnostic and so
    # they most likely won't be using an os.PathLike object in the sublists.
    if not isinstance(m[0], (list, tuple)):
        m = tuple(map(os.fspath, m))
    s1 = min(m)
    s2 = max(m)
    for i, c in enumerate(s1)://枚举得到s1的每一个字符及其索引
        if c != s2[i]:
            return s1[:i]
    return s1

Nevertheless, py3 this code execution speed is still much slower than Java.

NOTE: ASCll code comparison is not in accordance with the size and Comparative ASCll accumulation of all characters from the first character string a size comparison, if not the same size of the result obtained directly behind the characters are not compared.

Guess you like

Origin www.cnblogs.com/zhangzhe532/p/11105341.html