【LeetCode】8.Array and String —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().

这一题比较简单,常规思路可以解决。记得本科的时候学过一种可以减少时间复杂度的方法,当比对到的字母不一致时,之后的几位字母也不会一致,向后滑动一定的位置,这样可以减少不必要的比较,具体方法讨论区已经有人给出,在这里不在赘述。加油~

class Solution {
public:
int strStr(string haystack, string needle)
{
    if (needle == "") { return 0; } //根据题意进行空串检测 由提交后给的测试用例得出
    for (int i = 0; i < haystack.size(); i++) //以第一个串长设置外层循环
    {
        int sameNum = 0; //检测连续相同字母个数
        int counter = i; //设置计数器,用于遍历haystack[]来与needle比对
        if (haystack[counter] == needle[0]) {
            for (int j = 0; j < needle.size(); j++)
            {
                if (haystack[counter] == needle[j]) {//字母比对相同
                    counter++; 
                    sameNum++;
                }
                else break;
            }
            if (sameNum == needle.size()) return i;
        }
    }
    return -1;
}
};

猜你喜欢

转载自www.cnblogs.com/hu-19941213/p/10955135.html
今日推荐