編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 ""
。
示例 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);
}
}
提交結果: