leetcode 28 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

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().

不愧是easy等级的题目,so easy

class Solution {
public:
    bool isMatch(string s, string p, int m, int n, int len){
        for(int i=0;i<len;i++){
            if(s[m+i] != p[n+i]){
                return false;
            }
        }
        return true;
    }
    int strStr(string haystack, string needle) {
        int len_hay = haystack.length();
        int len_needle = needle.length();
        if(0 == len_needle){
            return 0;
        }
        if(len_hay<len_needle){return -1;}
        for(int i=0;i<len_hay-len_needle+1;i++){
            if (isMatch(haystack,needle,i,0,len_needle)){
                return i;
            }
        }
        return -1;
    }
};

猜你喜欢

转载自www.cnblogs.com/mangmangbiluo/p/9894744.html