题目如下:
Write a function to find the longest common prefix string amongst an array of strings.
意思就是说写一个方法返回一个字符串数组中每个字符串共有的开头。比如:{“1235”,”152”,”14”},就要返回”1”;又或者{“2235”,”52”,”41”},就要返回”“(空字符串)。
实现方法如下:
ps: Runtime = 10ms; beats87.19%
/**
* 当common为空字符串时,common.length = 0,common = "".
* common.substring(0,0) = "".
* common.indexOf("")=0
*/
public static String longestCommonPrefix1(String[] strs) {
if(strs.length==0) {return "";}
String common = strs[0];
for(int i=1;i<strs.length;i++){
while(strs[i].indexOf(common)!=0){
common = common.substring(0, common.length()-1);
}
if(common.equals("")){return common;}
}
return common;
}
涉及知识点:
1.空字符串的长度为0,空字符串=“”;
2.substring方法:
- (1)”123456”.substring(0,5) = “12345”(不包含编号为5的值);
- (2)字符串进行substring(0,0) = “”;
3.字符串进行indexOf(“”) = 0;