Implement strStr()

来源:互联网 发布:淘宝商城 天猫渔具 编辑:程序博客网 时间:2024/06/10 09:24

1、要记住这种用双重循环的查找方法;

for(int i=0;i<=lengthA-lengthB;++i)        {            bool flag=true;            for(int j=0;j<lengthB;++j)            {                if(haystack[i+j]!=needle[j])                {                    flag=false;                    break;                }            }            if(flag) return i;        }

题目:
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
查找haystack中是否有needle字符串,如果有返回其索引位置,没有返回-1;
思路:
1、判断字符串的长短,如果needle长度小于haystack的长度,返回-1;
2、如果两者长度相等,则判断两者是否完全相等;
3、如果haystack的长度较长,则用双重循环来判断;
代码:

class Solution {public:    int strStr(char *haystack, char *needle) {        int lengthA=strlen(haystack);        int lengthB=strlen(needle);        if(lengthA<lengthB) return -1;        if(lengthA==lengthB)         {            if(strcmp(haystack,needle)==0)  return 0;            else { return -1;}        }        for(int i=0;i<=lengthA-lengthB;++i)        {            bool flag=true;            for(int j=0;j<lengthB;++j)            {                if(haystack[i+j]!=needle[j])                {                    flag=false;                    break;                }            }            if(flag) return i;        }        return -1;    }};
0 0
原创粉丝点击