Write a function to find the longest common prefix string amongst an array of strings.
自己的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class Solution { public String longestCommonPrefix(String[] strs) { //当字符串数组strs为空,前缀为空字符串 if (strs.length== 0 ){ return "" ; } //定义初始前缀 String prefix = strs[ 0 ]; //将前缀和各字符串依次比较 for ( int i= 0 ;i<strs.length;i++){ //如果前缀为空,或者字符串数组strs的某个子字符串为空,返回空字符串 if (prefix.length()== 0 ||strs[i].length()== 0 ){ return "" ; } //找到前缀字符串和当前字符串之间的最短长度 int len = Math.min(prefix.length(),strs[i].length()); //比较前缀字符串和当前字符串,找出公共前缀 int j= 0 ; for (;j<len;j++){ //如果有不同的字符,直接跳出循环 if (prefix.charAt(j)!=strs[i].charAt(j)){ break ; } } //更新前缀 prefix = prefix.substring( 0 ,j); } return prefix; } }
|
Write a function to find the longest common prefix string amongst an array of strings.
自己的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class Solution { public String longestCommonPrefix(String[] strs) { //当字符串数组strs为空,前缀为空字符串 if (strs.length== 0 ){ return "" ; } //定义初始前缀 String prefix = strs[ 0 ]; //将前缀和各字符串依次比较 for ( int i= 0 ;i<strs.length;i++){ //如果前缀为空,或者字符串数组strs的某个子字符串为空,返回空字符串 if (prefix.length()== 0 ||strs[i].length()== 0 ){ return "" ; } //找到前缀字符串和当前字符串之间的最短长度 int len = Math.min(prefix.length(),strs[i].length()); //比较前缀字符串和当前字符串,找出公共前缀 int j= 0 ; for (;j<len;j++){ //如果有不同的字符,直接跳出循环 if (prefix.charAt(j)!=strs[i].charAt(j)){ break ; } } //更新前缀 prefix = prefix.substring( 0 ,j); } return prefix; } }
|