Longest Common Prefix (Python + Java)

Write a function to find the longest common prefix in an array of strings.
Returns the empty string "" if no common prefix exists.
Example 1:

Input: strs = ["flower", "flow", "flight"]
Output: "fl"

Example 2:

Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation: No common prefix exists for the inputs.

Idea 1: Take the first element in the list as the ruler, and take the prefix of the first string from "" to match each string in the list.
Python:

def longestCommonPrefix(strs):
    s, s1= '', ''
    if not strs[0]:  # [""] 的处理
        return ""
    flag = 0
    for i in range(len(strs[0])):
        s = s1
        s1 = strs[0][0:i + 1]  # 第一个字符串的前缀
        for el in strs:  # 遍历每个字符串
            if s1 == el[0:i+1]:
                flag = 1  # 标志遍历到相同前缀 ['a']  ['as','as] 针对相同元素
                continue
            else:
                return s
    if flag == 1:
        return s1

Result:
insert image description here
Idea 2 (opposite): use the first string (others are also acceptable) as a prefix, java comes with the startsWith() method to detect whether the string starts with the specified prefix, iterate through the data, and if the common prefix does not match, then Make the prefix shorter (i.e. the first string).
Java:

package learn;
// 最长公共前缀
public class LongestCommonPrefix {
    
    
    public static void main(String[] arg){
    
    
        String[] a = {
    
    "flower","flow","flight"};
        System.out.println(longestCommonPrefix(a));
    }

    public static String longestCommonPrefix(String[] strs) {
    
    
        //公共前缀比所有字符串都短,其实选择任意一字符串都可
        String s = strs[0];
        for (String string : strs) {
    
    
            while(!string.startsWith(s)){
    
    
                if(s.length() == 0) return "";
                // 公共前缀不匹配则变短
                s = s.substring(0,s.length()-1);
            }
        }
        return s;
    }
}

Guess you like

Origin blog.csdn.net/qq_43325582/article/details/122499336