Leetcode14

Leetcode 14

要求,编写一个函数来查找字符串组中的最长公共前缀

使用了Java语言编写,主要是利用函数indexOf和substring,从而进行比较和剪切。

public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length < 1)
            return "";
        String a=strs[0];
        for(int i=1;i<strs.length;i++){
            while(strs[i].indexOf(a)!=0){//进行比较
                a=a.substring(0,a.length()-1);//裁剪字符串
                if(a.isEmpty()){//如果裁剪的字符串是空串
                    return "";
                }
            }
        }
        return a;
    }
这是小睿的博客,如果需要转载,请标注出处啦~ヾ(≧▽≦*)o谢谢。
原文地址:https://www.cnblogs.com/Yunrui-blogs/p/12303990.html