28. Implement strStr()(easy)

版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/86529228

Easy

7241117FavoriteShare

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

 

C++:

/*
 @Date    : 2019-01-15 20:46:07
 @Author  : 酸饺子 ([email protected])
 @Link    : https://github.com/SourDumplings
 @Version : $Id$
*/

/*
https://leetcode.com/problems/implement-strstr/
 */

class Solution
{
public:
    int strStr(string haystack, string needle)
    {
        if (needle.empty())
        {
            return 0;
        }
        return haystack.find(needle);
    }
};

Java:

扫描二维码关注公众号,回复: 4963922 查看本文章
/**
 * @Date    : 2019-01-15 20:49:24
 * @Author  : 酸饺子 ([email protected])
 * @Link    : https://github.com/SourDumplings
 * @Version : $Id$
 *
 * https://leetcode.com/problems/implement-strstr/
*/

class Solution
{
    public int strStr(String haystack, String needle)
    {
        return haystack.indexOf(needle);
    }
}

猜你喜欢

转载自blog.csdn.net/SourDumplings/article/details/86529228
今日推荐