实现strStr()(leetcode28)

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,

在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。

如果不存在,则返回  -1。

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

 

解析:

方法一:子串逐一比较 

最直接的方法 - 沿着字符换逐步移动滑动窗口,将窗口内的子串与 needle 字符串比较

复制代码
public class leetcode28 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String haystack = "hello";
        String needle = "ll";
        System.out.println(strStr(haystack,needle));
    }
    
    public static int strStr(String haystack,String needle){
        int n = haystack.length();
        int l = needle.length();

        for(int i=0;i<n-l+1;i++){
            if(haystack.substring(i,i+l).equals(needle)){
                return i;
            }
        }
        return -1;
    }

}
复制代码

方法二:双指针

上一个方法的缺陷是会将haystack所有长度L的子串都与needle比较,实际上不需要。

首先,只有子串的第一个字符跟needle字符串第一个字符相同的时候才比较。

其次,可以一个字符一个字符的比较,一旦不匹配了就立刻终止。

如下图,比较到最后一位发现不匹配,然后开始回溯。

需要注意,pn指针是移动到pn = pn - curr_len + 1的位置,而不是pn = pn - curr_len的位置。

即移动到下一个开始的位置,再依次对比。

算法

移动 pn 指针,直到 pn 所指向位置的字符与 needle 字符串第一个字符相等。

通过 pn,pL,curr_len 计算匹配长度。

如果完全匹配(即 curr_len == L),返回匹配子串的起始坐标(即 pn - L)。

如果不完全匹配,回溯。使 pn = pn - curr_len + 1, pL = 0, curr_len = 0。

复制代码
class Solution {
  public int strStr(String haystack, String needle) {
    int L = needle.length(), n = haystack.length();
    if (L == 0) return 0;

    int pn = 0;
    while (pn < n - L + 1) {
      // find the position of the first needle character
      // in the haystack string
      while (pn < n - L + 1 && haystack.charAt(pn) != needle.charAt(0)) ++pn;

      // compute the max match string
      int currLen = 0, pL = 0;
      while (pL < L && pn < n && haystack.charAt(pn) == needle.charAt(pL)) {
        ++pn;
        ++pL;
        ++currLen;
      }

      // if the whole needle string is found,
      // return its start position
      if (currLen == L) return pn - L;

      // otherwise, backtrack
      pn = pn - currLen + 1;
    }
    return -1;
  }
}
复制代码

 

posted @   Vincent-yuan  阅读(75)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2020-03-09 前端学习(45)~正则表达式
2020-03-09 前端学习(44)~js学习(二十一):包装类
2020-03-09 前端学习(43)~js学习(二十):内置对象 - String
2020-03-09 前端学习(42)~js学习(十九):内置对象-Date
2020-03-09 前端学习(41)~js学习(十八):内置对象:Math
点击右上角即可分享
微信分享提示