【LeetCode - Java练习】28.实现strStr(简单)

1.题目描述

在这里插入图片描述

2.解题思路

子串逐一比较的解法最简单,将长度为 L 的滑动窗口沿着 haystack 字符串逐步移动,并将窗口内的子串与 needle 字符串相比较,如图所示
在这里插入图片描述

3.代码实现

class Solution {
    
    
  public int strStr(String haystack, String needle) {
    
    
    int L = needle.length(), n = haystack.length();

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

猜你喜欢

转载自blog.csdn.net/weixin_48683410/article/details/113795299