[LeedCode OJ]#28 Implement strStr()

来源:互联网 发布:自动加好友软件 编辑:程序博客网 时间:2024/06/06 09:50

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:libin493073668@sina.com】


题目链接: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;    }};


0 0
原创粉丝点击