leetcode解题报告(9):Implement strStr()

描述

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

分析

设置一个索引index,初始化为0,用于表示needle的下标。遍历haystack,如果发现haystack的当前元素和needle中下标为index的元素相等,就将index加1;若index已等于needle的长度,说明已经遍历完needle,找到了这个子串。这时候返回的值要为haystack中needle的第一个元素所在的位置,如,对于两个字符串a和b:

string a("aasssa");

string b("sa");

当找到这个子串的时候,对于a来说,它的下标i已经是5了,而要返回的值为4,即指向"sa"中的s的下标。此时对于b来说,其index的值为2,即它的长度。不失一般性,返回的值应为 i-index+1

若遍历完haystack时index仍不为needle的长度,说明没有找到子串,因此返回-1。

另外两个比较奇葩的边界情况是需要单独考虑的,第一个是:

string haystack("a");

string needle("");

这时候返回的居然是0而不是-1!

经测试,发现needle[0]输出的值为'a',和haystack的第一个元素刚好相等,因此返回0.而事实上这时候needle的长度是为0的。这是我无法理解的。

另外一个情况和上面的类似:

string haystack("");

string needle("");

这时候返回的也是0。

代码如下:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int index = 0;
        if((haystack[0] == 'a' && needle.size() == 0)
            || (haystack.size() == 0 && needle.size() == 0))return 0;
        for(int i = 0; i != haystack.size(); ++i){
            if(haystack[i] == needle[index]){
                ++index;
                if(index == needle.size())return i - index + 1;
            }else{
                i -= index;
                index = 0;
            }
            
        }
        return -1;
    }
};
posted @ 2017-04-25 16:08  larryking  阅读(132)  评论(0编辑  收藏  举报