Leetcode 详解(Implement strstr)

时间:2021-07-24 12:25:38

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

注:直接看题目可能会有些偏差,因为容易认为 needle是一个字符,那就也太容易了,实则,haystack和needle都是字符串(注意是字符串不是数组)

解法思路:

暴力搜索:

public class Solution {
  public int strStr(String haystack, String needle) {
    int i=0,j=0;
    while(i<haystack.length()&&j<=(needle.length()-1))
    {
      if(haystack.charAt(i)==needle.charAt(j))
      {
        i++;
         j++;
      }
      else
      {
        i=i-j+1;
        j=0;
      }
    }
    if(j==needle.length())
      return i-j;
    else return -1;
  }
}

感受下 clean code

public int strStr(String haystack, String needle) {
  for (int i = 0; ; i++) {
    for (int j = 0; ; j++) {
      if (j == needle.length()) return i;
      if (i + j == haystack.length()) return -1;
      if (needle.charAt(j) != haystack.charAt(i + j)) break;
      }
    }
}