LeetCode14- 最长公共前缀

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

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int n = strs.length;
        String s = "";
        if ( n == 0 ) {
            return s;
        }
        
        else if ( n == 1 ) {
            return strs[0];
        }
        
        else if ( n == 2 ) {
            return common( strs[0] , strs[1] );
        }
        
        else {
            s = common( strs[0] , strs[1] );
            for ( int i = 2 ; i < n ; i++ ) {
                if ( s == null ) {
                    break;
                }
                s = common( s , strs[i] );
            }
            return s;
        }
    }
    
    public String common( String s1 , String s2 ) {
        int n1 = s1.length();
        int n2 = s2.length();
        int i = 0;
        for ( i = 0 ; i < Math.min( n1 , n2 ) ; i++ ) {
            if ( s1.charAt(i) != s2.charAt(i) ) {
                break;
            }
        }
        return s1.substring(0 , i);
    }
}

 提交结果:

原文地址:https://www.cnblogs.com/cg-bestwishes/p/10693304.html