让我们写来看一道字符串的题(LeetCode第28题)
28. 实现 strStr()
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
暴力匹配思想:
- 依次从haystack的首字符开始,与needle逐一进行匹配;
- 遇到失配时,则移到haystack的第二个字符,将其与needle 首字符比较,逐一进行匹配;
- 重复上述步骤,直至能匹配上,或剩下haystack 的长度不足以进行匹配。
代码实现:
for循环:
/*暴力查找法(for循环)*/
public static int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0; //如果needle的长度为0,返回0;
for (int i = 0; i < haystack.length(); i++) {
char c = haystack.charAt(i);
if (c == needle.charAt(0)) { //当haystack的某个字符与needle的第一个匹配上
int a = 1;
for (int j = 1; j < needle.length(); j++) {
if ((i + j) >= haystack.length()) return -1;
else if (haystack.charAt(i + j) == needle.charAt(j)) a++; //每当匹配一次,让a+1;
else if (haystack.charAt(i + j) == needle.charAt(j)) continue; //当匹配不上时,后面的比较没有意义,直接跳过循环
}
if (a == needle.length()) return i; //当a==needle的长度时,返回此数i的值
}
}
return -1;
}
结果如下:
我们可以看到for循环的效率是非常低的.
while循环
while循环相对于for循环比较难理解
/*暴力查找法(while循环)*/
public static int strStr(String haystack, String needle) {
char[] a = haystack.toCharArray();
char[] b = needle.toCharArray();
int i = 0; //i索引指向数组a
int j = 0; //j索引指向数组b
while (i < a.length && j < b.length) { //保证匹配时不越界
if (a[i] == b[j]) {//匹配成功
j++;
i++;
} else { //没有匹配成功
//如果匹配失败,即a[i] != b[j] ,那么令i=i-j+1,j=0;
i = i - j + 1;
j = 0;
}
}
//判断是否匹配成功
if (j == b.length) {
return i - j;
} else {
return -1;
}
}
结果如下:
在这里我们可以看到while循环比for循环能更快一点,但是效率还是比较低的.