实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
自己用暴力方式做出来的
public int strStr(String haystack, String needle) {
//先取出来避免频繁取值
int haystackLength = haystack.length();
int needleLength = needle.length();
//要匹配的字符串长度为0,返回0
if (needleLength == 0) {
return 0;
}
//要匹配的子字符串长度大于母字符串,返回-1
if (haystackLength < needleLength) {
return -1;
}
//从母串一个个遍历
for (int i = 0; i < haystackLength; i++) {
//当发现两字符串取出的字符相等,且母串 (haystackLength-i) 剩余的要匹配的字符串长度大于子串时,才继续匹配
for (int j = 0; j < haystackLength - i && needle.charAt(j) == haystack.charAt(j + i); j++) {
//完全匹配了
if (j == needleLength - 1) {
return i;
}
}
}
return -1;
}