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

LeetCode 28. Implement strStr()

时间:2016-08-15 20:44:17      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

Implement strStr().

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

两个字符串A和B, 在A中查找是否出现过B, 如果出现就返回第一次出现的下标, 如果没有就返回-1

用暴力的方法求解,假设A字符串长度为N, B字符串长度为K, 则时间复杂度是N*K , LeetCode的评价是

技术分享

 程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    int strStr(string haystack, string needle) {
        int i=0;
        if(haystack.size()<needle.size())
            return -1;
        while(1)
        {
            //边界处理
            if(i>(haystack.size()-needle.size()))
                break;
            int flag=0;//记录是否会遇到不一致的字符
            int k=0;//needle的下标
            for(int j=0;j<needle.size();j++)
                if(needle[j]!=haystack[j+i]){
                    i++;
                    flag=1;
                    break;
                }
                else{
                    k++;
                }
            if(flag==0){
                return i;
            }
        }
        return -1;
    }
};





LeetCode 28. Implement strStr()

标签:

原文地址:http://www.cnblogs.com/gremount/p/5774155.html

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