Implement strStr()
Input: haystack = "hello", needle = "ll"
Output: 2Input: haystack = "aaaaa", needle = "bba"
Output: -1Input: haystack = "", needle = ""
Output: 0Solutions
π§ Cpp
Last updated
Input: haystack = "hello", needle = "ll"
Output: 2Input: haystack = "aaaaa", needle = "bba"
Output: -1Input: haystack = "", needle = ""
Output: 0Last updated
class Solution
{
public:
int strStr(string haystack, string needle)
{
if(haystack == needle || needle.empty())
return 0;
for(auto iter = begin(haystack);
iter < end(haystack);
++iter)
{
if(end(haystack) - iter < needle.size())
return -1;
if(*iter == needle.front())
{
bool are_same = false;
//check is chunk the same
for(auto iter_A = iter, iter_B = begin(needle);
iter_A < end(haystack) && iter_B < end(needle);
++iter_A, ++ iter_B
)
if(*iter_A != *iter_B)
break;
else if(next(iter_B) == end(needle))
are_same = true;
if(are_same)
return iter - begin(haystack);
}
}
return -1;
}
};