码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(28)题解:Implement strStr()

时间:2015-07-14 15:23:11      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/implement-strstr/

 

题目:

Implement strStr().

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

 

思路:

判断一个string是否另一个string的子序列并返回位置。

naive法:遍历查找,复杂度O(mn)。

advance法还有Rabin-Karp, KMP, Boyer- Moore algorithm等。

 

AC代码:

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) { 4         int m=haystack.size();
 5         int n=needle.size();
 6         if(n==0 && m==0)
 7             return 0;
 8         bool flag=true;
 9         for(int i=0;i<m-n+1;i++){
10             for(int j=0;j<n;j++){
11                 if(needle[j]!=haystack[i+j]){
12                     flag=false;
13                     break;
14                 }
15             }
16             if(flag==true){
17                 return i;
18             }
19             else
20                 flag=true;
21         }
22         return -1;
23     }
24 };

 

LeetCode(28)题解:Implement strStr()

标签:

原文地址:http://www.cnblogs.com/aezero/p/4645181.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!