Leetcode典型题解答和分析、归纳和汇总——T28(实现strStr())

题目描述:

给定一个haystack字符串和一个needle字符串,在haystack字符串中找出needle字符串出现的第一个位置(从0开始)。如果不存在,则返回-1.

解析:

【1】直接采用库函数的方法

class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);
    }
};

【2】采用暴力方法:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int i=0,j=0;
        while(i<haystack.size()&&j<needle.size()){  //遍历字符串
            if(haystack[i]==needle[j]) i++,j++;  //相等时,指针都+1
            else i=i-j+1,j=0;  //不相等时,i从下个指针开始匹配,j从0开始
        }
        if(j==needle.size()) return i-j;  //返回出现重复字符串开始位置
        return -1;
    }
};
发布了56 篇原创文章 · 获赞 7 · 访问量 4484

猜你喜欢

转载自blog.csdn.net/weixin_44504987/article/details/104338925