题目:Write a function to find the longest common prefix string amongst an array of strings.
解释:求输入字符串数组中最长的相同前缀
public class Solution {
public String longestCommonPrefix(String[] strs) {
int strsLen = strs.length;
String longestCommonPrefix = "";
if (strsLen < 1) {
return longestCommonPrefix;
}
// 最短字符串在字符串数组中的位置
int minIndex = 0;
// 最短字符串长度
int minestLen = strs[0].length();
for (int i = 1; i < strsLen; i++) {
int tempLen = strs[i].length();
if (tempLen < minestLen) {
minestLen = tempLen;
minIndex = i;
}
}
// 最短的字符串
char[] minStrChars = strs[minIndex].toCharArray();
// 最长的相同前缀不能比最短的字符串长
for (int j = 0; j < minestLen; j++) {
for (int i = 0; i < strsLen; i++) {
char[] temChars = strs[i].toCharArray();
if (temChars[j] != minStrChars[j]) {
return longestCommonPrefix;
}
}
longestCommonPrefix += minStrChars[j];
}
return longestCommonPrefix;
}
}