LeetCode刷题笔记--28. Implement strStr()

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

这道题比较简单,加了两个特殊情况就过了。一个特殊情况是haystack的长度小于needle的长度,另一个特殊情况是needle为“”’时返回0,这个情况在题目上有提示,说返回0是为了与C语言中strstr()函数保持一致。

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len=needle.length();
        int len1=haystack.length();
        if(len1<len)return -1;
        if(len==0)return 0;
        for(int i=0;i<haystack.length()-len+1;i++)
        {
            if(haystack.substr(i,len)==needle)return i;
        }
        return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/87972908