leetcode-28 implement-strstr(实现strStr)
想先看一下题目描述:

这个题很简单,但是我第一次做题的时候没有理解题意。needle里的元素要在haystack里全部体现。并且还需要注意数组越界问题。
1 public static int strStr(String haystack, String needle) {
2 int len = needle.length();
3 for (int i = 0; i < haystack.length() - len + 1; i++) {
4 if (haystack.substring(i, i + len).equals(needle))
5 return i;
6 }
7 return -1;
8 }
但是我不太理解为什么i < haystack.length() - len + 1,这样可以防止数组越界,但是原因还没有搞清楚。

浙公网安备 33010602011771号