Implement strStr()

简介: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 这个题应该就是求子串的问题,改进的方法是kmp算法。

Implement strStr().

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

这个题应该就是求子串的问题,改进的方法是kmp算法。

朴素算法的C++代码如下:

#include<iostream>
#include<cstring>
using namespace std;
class Solution {
public:
    int strStr(char *haystack, char *needle) {
        if(strlen(haystack)<strlen(needle))
            return -1;
        size_t i,j,k;
        for(i=0;i<=(strlen(haystack)-strlen(needle));i++)
        {
            k=i;
            for(j=0;j<strlen(needle);j++)
            {
                if(haystack[k]==needle[j])
                    k++;
                else
                    break;
            }
            if(j==strlen(needle))
                return i;
        }
        if(j==strlen(needle))
            return i;
        return -1;
    }
};

int main()
{
    Solution s;
    char s1[]="swwssswsss";
    char s2[]="sss";
    cout<<s.strStr(s1,s2)<<endl;
}

运行结果:

相关文章
|
2月前
gets()&puts()函数
gets()&puts()函数。
10 2
|
9月前
|
索引
KMP Implement
KMP Implement
32 0
|
编译器
warning C4995: strcat name was marked as #pragma deprecated
warning C4995: strcat name was marked as #pragma deprecated
62 0
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
54 0
LeetCode 241. Different Ways to Add Parentheses
LeetCode 205. Isomorphic Strings
给定两个字符串 s 和 t,判断它们是否是同构的。 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
55 0
LeetCode 205. Isomorphic Strings
|
算法 Java C语言
LeetCode 28:实现strStr() Implement strStr()
公众号:爱写bug(ID:icodebugs) 作者:爱写bug 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。
677 0
1108. Finding Average (20) sscanf() sprintf()
#include #include #include #include #include using namespace std; //sscanf() – 从一个字符串中读进与指定格式相符的数据 //sprintf() – 字符串格式化命令,主要功能是把格式化的数据写入某个字符串中。
907 0