LeetCode# 28 strStr()

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1:

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

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

采用双指针+回溯算法,先遍历长的字符串,找到是否和短字符串第一个字符匹配,若匹配则继续比较接下来两者是否相等。

class Solution {
    public int strStr(String haystack, String needle) {
      int len1 = haystack.length();
      int len2 = needle.length();
      if(len2 == 0)return 0;
      int p1 = 0;
      while(p1 < len1-len2+1){
          while(p1 < len1-len2+1 && haystack.charAt(p1) != needle.charAt(0))p1++;
          int curlen = 0;
          int p2 = 0;
          while(p1 < len1 && p2 < len2 && haystack.charAt(p1) == needle.charAt(p2)){
              p1++;
              p2++;
              curlen++;
          }
          if(curlen == len2)return p1-curlen;
          p1 = p1 - curlen + 1;
      }
        return -1;
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr

你可能感兴趣的:(算法类,字符串,leetcode)