28. Implement strStr()【力扣】

题意理解

在一个字符串A中查找另一个字符串B,返回另一个字符串B的首字符位置。若另一个字符串B为空,返回0;若字符串A为空,返回-1;若查找失败,返回-1.

知识点

字符串处理:算法思路是如果字符串B长度为0,直接返回0;设定first1指针指向字符串A首字符,遍历字符串A,设定两个游标i,j分别指向A、B的首字符,当两个游标指向的字符相等时,如果游标j到达了B的末尾,说明找到了B,返回first1;如果游标i到达了A的末尾,说明没有找到,返回-1.否则,当两个游标指向的字符不等时,first1指针后移一位。

其他

本思路参考了STL的search算法实现。C版的方法用到了'\0',不太好复用。

想到的一点,就是字符串,数组的操作其实是后面的图,树的基础。好好打好这个基础。后面才能顺利一点。

链接

http://www.cplusplus.com/reference/algorithm/search/

    int strStr(string haystack, string needle) {

        if (needle.size() == 0)
            return 0;
        int first1 = 0, first2 = 0;

        while(first1 < haystack.size())
        {
            int i = first1;
            int j = first2;
            while(haystack[i] == needle[j])
            {
                if (j == needle.size() - 1) return first1;
                if (i == haystack.size() - 1) return -1;
                i++;
                j++;
            }
            first1++;
        }
        return -1;
    }

猜你喜欢

转载自blog.csdn.net/xiexie1357/article/details/88100812