Implement strStr().

来源:互联网 发布:网络最好的诈骗文章 编辑:程序博客网 时间:2024/06/07 11:13

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

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

哈哈,刚开始思想被阻塞或者说不能熟悉使用JAVA String类自带的indexOf()方法时采用参考网上最笨的办法写的这种方法。下面是一行代码就被leetcode accpted的代码,,

class Solution {    public int strStr(String haystack, String needle) {        return haystack.indexOf(needle);    }}

被通过时,想哭死。。

原创粉丝点击