28. Implement strStr() 实现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

Difficulty: Easy

这道题让我们找出字符串中某个子字符串第一次出现的index.如果子字符串的长度为0,则返回0,如果子字符传的长度大于母字符串,则返回-1.遍历字符串的时候只需要遍历到剩下的长度等于字符串的位置即可.

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