leetcode【字符串】-----28. Implement strStr()(实现strStr函数)

1、题目描述

2、分析

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

        首先判断子字符串是否为空,若为空则返回1。再比较子字符串和源字符串的长度,如果子字符串长那么返回-1。接下来,对于源字符串中的字符,对子串进行遍历,若不等则跳出循环,如果一直没有跳出,那么说明出现子串。则返回起始位置。

3、代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.empty()) return 0;
        if (haystack.size() < needle.size()) return -1;
        for (int i = 0; i <= haystack.size() - needle.size(); ++i) {
            int j = 0;
            for (j = 0; j < needle.size(); ++j) {
                if (haystack[i + j] != needle[j]) break;
            }
            if (j == needle.size()) return i;
        }
        return -1;
    }
};

4、相关知识点

        string相关函数,找子串的方法。

        

posted @ 2019-04-01 22:03  吾之求索  阅读(122)  评论(0)    收藏  举报