首页 > 其他 > 详细

LeetCode 28. Implement strStr()

时间:2016-08-15 20:44:10      阅读:161      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!