首页 > 其他 > 详细

【LeetCode】8.Array and String —Implement strStr() 查找中枢索引

时间:2019-05-31 16:29:13      阅读:88      评论:0      收藏:0      [点我收藏+]

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;
}
};

 

【LeetCode】8.Array and String —Implement strStr() 查找中枢索引

原文:https://www.cnblogs.com/hu-19941213/p/10955135.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!