Implement strStr()

来源:互联网 发布:淘宝店现在还挣钱么 编辑:程序博客网 时间:2024/06/02 04:03

Implement strStr().

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

就是在字符串haystack中找到needle 的位置。。。

class Solution {public:    int strStr(string haystack, string needle) {       int m = haystack.size();        int n = needle.size();        for(int i = 0; i <= m-n; i ++)        {            int j;            for(j = 0; j < n; j ++)            {                if(haystack[i+j] != needle[j])                    break;            }            if(j == n)                return i;        }        return -1;    }};

#include<string>#include<iostream>#include<algorithm>using namespace std;int strstr(string, string);int main(){string a = "asdfghjklzxcvb";string b = "lzxcvb";cout << strstr(a, b);system("pause");return 0;}int strstr(string a, string b){int len1 = a.size();int len2 = b.size();if (len1 < len2)return -1;int j;for (int i = 0; i < len1; i++){for (j = 0; j < len2; j++){if (a[i + j] != b[j])break;}if (j == len2)return i;}return -1;}



还有KMP算法  还不懂呢

0 0
原创粉丝点击