[C++] Implement strStr()

 

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

strstr()函数返回匹配的首字符索引。

可以使用常规的匹配算法,蛮力算法

遍历haystack到m-n+1的同时遍历needle从0到n,while来判断两个string对应字符是否相等。

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.size(), n = needle.size();
        if (n == 0)
            return 0;
        for (int i = 0; i < m - n + 1; i++) {
            int j = 0;
            while (haystack[i + j] == needle[j]) {
                j++;
                if (j == n)
                    return i;
            }
            j++;
        }
        return -1;
    }
};
// 6 ms
原文地址:https://www.cnblogs.com/immjc/p/8044847.html