算法十四:最长公共前缀

算法内容

编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 “”。

示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”

示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:""
解释:输入不存在公共前缀。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix

算法思想

该算法比较简单,双层循环便可解决,这也是最容易想到的方法,这里便不再详细讲述算法思想,直接看整体算法便可理解。

整体算法

public class Day_14 {
    
    
    public static String longestCommonPrefix(String[] strs) {
    
    
        int target=1;
        String s="";
        if (strs.length==0||strs[0].isEmpty()){
    
    
            return s;
        }
        char q;
        for (int i = 0; i < strs[0].length(); i++) {
    
    
            q=strs[0].charAt(i);
            for (target = 1; target <strs.length ; target++) {
    
    
                if (strs[target].length()>i){
    
    
                    if(q!=strs[target].charAt(i)){
    
    
                        return s;
                    }
                }else{
    
    
                    return s;
                }
            }
            if(target==strs.length){
    
    
                s+=q;
            }
        }
       return s;
    }
    public static void main(String[] args) {
    
    
        String [] strs={
    
    ""};
        System.out.println(longestCommonPrefix(strs));
    }
}

尾语

以上属于个人见解,有好的想法可以在下方评论写出自己的想法,大家一起进步。该题是力扣上的题,若有侵权,请及时告知。该题链接:https://leetcode-cn.com/problems/longest-common-prefix

猜你喜欢

转载自blog.csdn.net/weixin_40741512/article/details/113355465