[LeetCode]28. Implement strStr()

实现自己的substr

Posted by JinFei on March 27, 2020

题目描述

Implement strStr().

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

Example1:

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

Example2:

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

Clarification:

  • What should we return when needle is an empty string? This is a great question to ask during an interview.
  • For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.size() == 0){
            return 0;
        }
        int n = haystack.size();
        int m = needle.size();
        for(int i = 0; i <= n - m; i++){
            int j = 0;
            for(; j < m; j++){
                if(haystack[i + j] != needle[j]){
                    break;
                }
            }
            if(j == m){
                return i;   // 如果最后匹配成功,那么肯定是从i开始匹配的,我们只需要返回i即可
            }
        }
        return -1;
    }
};