LeetCode(14)获取字符串数组中字符串的公共前缀
问题:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
java解答
class Solution {
/**
* 思路
* 根据这个字符串数组中最短的字符串的长度,确定遍历的次数
* 在每次遍历中,遍历每个字符串,依次从首个字符串的首个字符开始,分别与每个字符串的对应位置的字符比较
* 如果不等,则break,如果一次遍历过程结束,没有break,将这个字符放到结果字符串中
*/
//结果字符串
private String result = "";
//字符串数组中最短字符串的长度
private int minStr = 0;
//获取这个字符串数组中最短字符串的长度
public void getMinStr(String[] strs){
if(strs.length < 1){
return;
}
int temp = strs[0].length();
for(String str:strs){
if(temp>str.length()){
temp = str.length();
}
}
this.minStr = temp;
}
//遍历字符串数组,存放结果
public void getLongestCommonPrefix(String[] strs){
for(int i = 0;i < this.minStr; i++){
for(int j = 1; j < strs.length; j++){
if(strs[0].charAt(i) != strs[j].charAt(i)){
return;
}
}
this.result += strs[0].charAt(i);
}
}
public String longestCommonPrefix(String[] strs) {
if(strs.length < 1){
return "";
}else if(strs.length == 1){
return strs[0];
}
this.getMinStr(strs);
this.getLongestCommonPrefix(strs);
return this.result;
}
}