实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
当 needle 是空字符串时,返回 0
示例 1:
输入:haystack = “hello”, needle = “ll”
输出:2
示例 2:
输入:haystack = “aaaaa”, needle = “bba”
输出:-1
public int strStr(String haystack, String needle) {// needle 空字符串,返回 0if ("".equals(needle)) {return 0;}// needle 比 haystack 长,必定不存在if (needle.length() > haystack.length()) {return -1;}for(int i = 0; i < haystack.length(); i++) {// 依次比较字符char c = haystack.charAt(i);if (needle.charAt(0) == c) {// 若遇到字符相同,比较 haystack 剩余长度是否足够,若不足,则必然不存在if ((i + needle.length()) > haystack.length()) {break;}// 截取 haystack 剩余部分字符串,并且和 needle 比较,若相等,则 i 即出现的第一个位置String subHaystack = haystack.substring(i, i + needle.length());if (subHaystack.equals(needle)) {return i;}}}return -1;}
其实后半部分即字符串匹配问题,可以利用 BF 算法进行字符串匹配:
public int strStr(String haystack, String needle) {// needle 空字符串,返回 0if ("".equals(needle)) {return 0;}// needle 比 haystack 长,必定不存在if (needle.length() > haystack.length()) {return -1;}return bfMatch(haystack, needle, 0);}public int bfMatch(String str, String sub, int pos) {if (pos < 0 || pos > str.length()) {return -1;}int baseIndex = pos;int index = 0;while(baseIndex < str.length() && index < sub.length()) {if (str.charAt(baseIndex) == sub.charAt(index)) {// 字符匹配baseIndex++;index++;} else {// 主串回退从新开始匹配baseIndex = baseIndex - index + 1;index = 0;}}if (index >= sub.length()) {// 子串匹配结束,计算匹配的起始位置return baseIndex - index;}return -1;}
而字符串匹配 BF 算法可以优化为 RF 算法,KMP 算法等等
