设为首页 加入收藏

TOP

LeetCode 28 Implement strStr()
2015-11-21 00:55:04 来源: 作者: 【 】 浏览:1
Tags:LeetCode Implement strStr

翻译

实现strStr()函数。

返回针(needle)在草垛/针垛(haystack)上第一次出现的索引, 如果不存在其中则返回-1。

其实也就是说字符串str2在字符串str1中第一次出现的索引而已。

原文

Implement strStr().

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

代码

class Solution {
public:
    bool compare(string s1, int index, string s2) {
        int count = 0;
        for (int i = 0; i < s2.length(); i++) {
            if (s2[i] == s1[i + index])
                count++;
        }
        if (count == s2.length())
            return true;
        return false;
    }         
    int strStr(string haystack, string needle) {
        for (int i = 0; i < haystack.length(); i++) {
            if (haystack[i] == needle[0]) {
                if (compare(haystack, i, needle))
                    return i;
            }
        }
        return -1;
    }
};

发现超时了……其实在测试之前就看到了别人的答案……惊呆了……这样都可以?

 class Solution {
    public:
        int strStr(string haystack, string needle) {

            return haystack.find(needle);

        }
    };

也算是长见识了……

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 1813(IDA*算法+dfs) 下一篇[LeetCode从零单刷]Intersection ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: