天天看点

Leetcode初学——最长公共前缀

题目

Leetcode初学——最长公共前缀

我认为这道题就是重复的遍历数组,直到出现不同项为止,算是比较简单的题目

代码如下:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        String res="";
        int i=0;
        if(strs.length==1) return strs[0];
        for(int j=0;j< strs.length;j++) {
            if (i == strs[j].length() || i >= strs[0].length()) break;
            if(j==0) continue;
            if ( strs[j].charAt(i) == strs[0].charAt(i)){
                if(j==strs.length-1) res+=strs[0].charAt(i++);
            }
            else break;
            if(j==strs.length-1) j=0;
        }
        return res;
    }
}
           

结果如下:

Leetcode初学——最长公共前缀

看到官方解答中有一个更简单的代码:

public String longestCommonPrefix(String[] strs) {
   if (strs.length == 0) return "";
   String prefix = strs[0];
   for (int i = 1; i < strs.length; i++)
       while (strs[i].indexOf(prefix) != 0) {
           prefix = prefix.substring(0, prefix.length() - 1);
           if (prefix.isEmpty()) return "";
       }        
   return prefix;
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
           

看完之后只想感慨一句:真的是对java的方法很熟悉了啊