[leetcode] 28. Implement strStr() 解题报告

题目链接:https://leetcode.com/problems/implement-strstr/

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.


思路:很简单的一题,就是找一个字符串中是否包含另一个字符串,并返回其位置。

代码如下:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int i = 0, len1 = haystack.size(), len2 = needle.size();
        while(i <=  len1- len2)
        {
            string tem = haystack.substr(i, len2);
            if(tem == needle)
                return i;
            i++;
        }
        return -1;
    }
};


你可能感兴趣的:(LeetCode,算法,String)