您的位置:首页 > 其它

[LeedCode OJ]#28 Implement strStr()

2015-08-24 12:41 295 查看
[b]【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】

[/b]



题目链接:https://leetcode.com/problems/implement-strstr/



题意:

给定两个串,判定needle串是否haystack串的子串,如果是,返回匹配的起始位置,如果不是,则返回-1



思路:

直接两个循环暴力解决

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        int len1 = haystack.length(),len2 = needle.length();
        int i,j;
        if(len2>len1) return -1;
        if(len1 == len2 && haystack!=needle) return -1;
        for(i = 0; i<=len1-len2; i++)
        {
            for(j = 0; j<len2; j++)
            {
                if(haystack[i+j]!=needle[j])
                    break;
            }
            if(j == len2)
                return i;
        }
        return -1;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: