【LeetCode】28. Implement strStr()

Implement strStr().

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

题意:返回在字符串中子字符串出现的第一个位置,没有返回-1

这几个题都好简单啊,

1 class Solution(object):
2     def strStr(self, haystack, needle):
3         """
4         :type haystack: str
5         :type needle: str
6         :rtype: int
7         """
8         n=haystack.find(needle)
9         return n

 暴力C:

 1 int strStr(char* haystack, char* needle) {
 2     int i,j;
 3     int hl,nl;
 4     hl=strlen(haystack);
 5     nl=strlen(needle);
 6     if(nl==0)
 7         return 0;
 8     if(hl<nl)
 9         return -1;
10     for(i=0;i<hl-nl+1;i++){
11         for(j=0;j<nl;j++){
12             if(haystack[i+j]!=needle[j])
13                 break;
14             if(j==nl-1)
15                 return i;
16         }
17     }
18     return -1;
19 }

 还有一种KMP算法,一直想学,一直拖,这两天学会了放上来

原文地址:https://www.cnblogs.com/fcyworld/p/6217219.html