题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
解题
String longestCommonPrefix(String[] strs){
if (strs.length == 0) {
return "";
}
String prefix = strs[0];
//
for (int i = 1; i < strs.length; i++) {
// 第一次出现的位置 起始位置
while (strs[i].indexOf(prefix) != 0) {
// 如果不是从0 起始位置开始出现 则prefix 减去一个字符
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
在一般情况大多想的相加,这里的解决方法也是官方题解的第一种解法,非常巧妙的运用了 indexOf()方法,下面是对 indexOf方法的源码进行解读
/**
* Returns the index within this string of the first occurrence of the
* specified substring.
* 返回此字符串中第一个出现的指定的子字符串
* 不存在则返回 -1
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the first occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str) {
return indexOf(str, 0);
}
/**
* 要搜索的字符串
* @param str the substring to search for.
* 开始搜索的索引
* @param fromIndex the index from which to start the search.
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
/**
*
* @param source 正在搜索的字符。
* @param sourceOffset 源字符串的偏移量。
* @param sourceCount 源字符串的计数。.
* @param target 正在搜索的字符。
* @param targetOffset 目标字符串的偏移量.
* @param targetCount 目标字符串的计数。
* @param fromIndex 开始搜索的索引。
*/
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
// 下面三个是对于起始搜索位置.目标长度的特殊情况直接返回
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
// 目标字符串的第一个char
char first = target[targetOffset];
//取最后一次搜索的位置
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
// 找到第一个相同的char的位置
if (source[i] != first) {
// 这个循环很优秀,值得学习
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
//再次判断
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
//循环遍历往后的字符是否相等
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}