14. Longest Common Prefix
- Total Accepted: 112204
- Total Submissions: 385070
- Difficulty: Easy
Write a function to find the longest common prefix string amongst an array of strings.
思路:
题目很简单,求字符串数组的最长的共同前缀。也没什么思路,诸位比较呗,代码如下:
public class No_014 {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0){
return "" ;
}
StringBuilder res = new StringBuilder() ;
//通过flag标志位来判断是否结束循环,以及是否应该加入返回的结果中
boolean flag = true ;
int index = 0 ;
while(flag){
char ch ;
if(index < strs[0].length()){
ch = strs[0].charAt(index) ;
}else{
flag = false ;
continue ;
}
for(int i = 1 ; i < strs.length ; i++){
if(index < strs[i].length() && strs[i].charAt(index) == ch){
continue ;
}else{
flag = false ;
break ;
}
}
//通过判断flag的值来判断是否是满足所有条件的
if(flag){
res.append(ch) ;
index++ ;
}
}
return res.toString() ;
}
}