문자열 haystack과 needle을 받는다.
haystack에서 needle 문자열이 처음 나오는 인덱스를 반환하고,
존재하지 않을 시 -1을 반환해야 하는 문제
class Solution {
public:
int strStr(string haystack, string needle) {
int targetLength = needle.length();
int targetIndex{0};
for (int i = 0; i < haystack.size(); ++i)
{
if (haystack[i] == needle[targetIndex])
{
++targetIndex;
if (targetIndex == targetLength)
{
return i - targetLength + 1;
}
}
else
{
i -= targetIndex;
targetIndex = 0;
}
}
return -1;
}
};