Write a function to find the longest common prefix string amongst an array of strings.
思路:设置一个字符串截取窗口(用于截取字符串的前缀),遍历字符串数组,对每个字符串截取一定长度的字符串部分,设置一个标志step,用equals方法比较两两相邻的字符串是否相等,若相等则step++,若step 等于数组长度-1,则表示字符串截取窗口走到了字符串数组末尾元素位置(最后一个字符串元素),然后再一步步增加截取窗口的长度,重复以上操作。
Java代码实现
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0 || strs == null)
return "";
if(strs.length == 1)
return strs[0];
String prefix = "";
int len = strs[0].length();
//找到最短字符串的长度,设置为字符串窗口的最大长度
for(int i = 1; i < strs.length; i++){
if(strs[i].length() < len){
len = strs[i].length();
}
}
//最外层循环表示截取窗口的大小
for(int i = 0; i < len; i++){
int step = 0;
//遍历字符串数组,比较对两两相邻的字符串截取后的字符串进行比较
for(int j = 0; j < strs.length - 1; j++){
if(strs[j].substring(0, i+1).equals(strs[j+1].substring(0, i+1))){
step++;
}
}
//判断截取窗口是否走到最后
if(step == strs.length - 1){
prefix = strs[0].substring(0, i+1);
}
}
return prefix;
}
}