实现 strStr() 函数。
    给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
    当 needle 是空字符串时,返回 0

    示例 1:
    输入:haystack = “hello”, needle = “ll”
    输出:2

    示例 2:
    输入:haystack = “aaaaa”, needle = “bba”
    输出:-1

    1. public int strStr(String haystack, String needle) {
    2. // needle 空字符串,返回 0
    3. if ("".equals(needle)) {
    4. return 0;
    5. }
    6. // needle 比 haystack 长,必定不存在
    7. if (needle.length() > haystack.length()) {
    8. return -1;
    9. }
    10. for(int i = 0; i < haystack.length(); i++) {
    11. // 依次比较字符
    12. char c = haystack.charAt(i);
    13. if (needle.charAt(0) == c) {
    14. // 若遇到字符相同,比较 haystack 剩余长度是否足够,若不足,则必然不存在
    15. if ((i + needle.length()) > haystack.length()) {
    16. break;
    17. }
    18. // 截取 haystack 剩余部分字符串,并且和 needle 比较,若相等,则 i 即出现的第一个位置
    19. String subHaystack = haystack.substring(i, i + needle.length());
    20. if (subHaystack.equals(needle)) {
    21. return i;
    22. }
    23. }
    24. }
    25. return -1;
    26. }

    其实后半部分即字符串匹配问题,可以利用 BF 算法进行字符串匹配:

    1. public int strStr(String haystack, String needle) {
    2. // needle 空字符串,返回 0
    3. if ("".equals(needle)) {
    4. return 0;
    5. }
    6. // needle 比 haystack 长,必定不存在
    7. if (needle.length() > haystack.length()) {
    8. return -1;
    9. }
    10. return bfMatch(haystack, needle, 0);
    11. }
    12. public int bfMatch(String str, String sub, int pos) {
    13. if (pos < 0 || pos > str.length()) {
    14. return -1;
    15. }
    16. int baseIndex = pos;
    17. int index = 0;
    18. while(baseIndex < str.length() && index < sub.length()) {
    19. if (str.charAt(baseIndex) == sub.charAt(index)) {
    20. // 字符匹配
    21. baseIndex++;
    22. index++;
    23. } else {
    24. // 主串回退从新开始匹配
    25. baseIndex = baseIndex - index + 1;
    26. index = 0;
    27. }
    28. }
    29. if (index >= sub.length()) {
    30. // 子串匹配结束,计算匹配的起始位置
    31. return baseIndex - index;
    32. }
    33. return -1;
    34. }

    而字符串匹配 BF 算法可以优化为 RF 算法,KMP 算法等等