LeeCode from 0 ——28. Implement strStr()

28. Implement strStr()

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

解题思路:

1)判断needle字符串长度,等于0,返回0;

2)若haystack长度小于needle,返回-1;

3)s.substr(pos, n)函数,pos为起始位置,n为个数,例如s="12345iuy",s.substr(1,4)="2345"。利用该函数,比较haystack中是否存在needle,若存在返回起始位置,若不存在返回-1。

代码如下:

class Solution {
public:
int strStr(string haystack, string needle) {
        int m=haystack.length();
        int n=needle.length();
        if(n==0)
                return 0;
        else if(m<n)
               return -1;
        else{
               for(int i=0;i+n<=m;i++){
                        if(haystack.substr(i,n)==needle)
                            return i;
               }
              return -1;
       }

}
};

posted @ 2018-06-13 15:48  ssml  阅读(57)  评论(0编辑  收藏  举报