首页 > 其他 > 详细

【Implement strStr() 】cpp

时间:2015-05-03 23:29:58      阅读:193      评论:0      收藏:0      [点我收藏+]

题目

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        const size_t len_hay = haystack.size();
        const size_t len_nee = needle.size();
        if ( len_hay < len_nee ) return -1;
        bool if_match = true;
        for ( size_t i = 0; i <= len_hay-len_nee; ++i )
        {
            if_match = true;
            for ( size_t j = 0; j < len_nee; ++j ){
                if (haystack[i+j]!=needle[j]){
                    if_match = false;
                    break;
                }
            }
            if ( if_match ){
                return i;
            }
        }
        return -1;
    }
};

Tips:

利用标志变量,暴力解决方法。时间复杂度O(m×n),空间复杂度O(1)

貌似还有个KMP算法,这个可以做到O(m+n)的时间复杂度,但是空间复杂度牺牲到了O(m)。明天再看KMP算法,这个效率的提升还是蛮高的,直接提高到了线性复杂度。

【Implement strStr() 】cpp

原文:http://www.cnblogs.com/xbf9xbf/p/4474888.html

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