题目相关
【题目解读】
实现 strStr(string haystack, string needle) 函数,返回 needle在 haystack中第一次出现的位置,如果没有出现返回-1.
【原题描述】原题链接
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
【难度】Easy
Solution
最简单的方法,调用string中的find函数求解,具体如下:
int strStr(string haystack, string needle) {
if ( needle.empty() )
{
return 0;
}else if(haystack.empty())
{
return -1;
}
return haystack.find(needle);
}
有一点需要注意,上面判断 needle和 haystack 是否为空的情况。
最开始我使用的是如下判断,当haystack为空,eg:“”, needle为非空,eg:“bb”,此时如下判断将会直接返回0,而实际上needle不为空,所以这样的结果有问题,需要修正为上面的正确解法。
if (haystack.empty() || needle.empty())
{
return 0;
}