leetcode

来源:互联网 发布:python timer缺点 编辑:程序博客网 时间:2024/06/07 19:13

Question28–Implement strStr()

给出一个字符串在另一个字符串中第一次出现的索引,若没出现返回-1

算法

遍历比较,注意几种特殊情况就好

Code

int strStr(string haystack, string needle) {        int haysize=haystack.size(), needsize=needle.size();        if(needsize==0) return 0;        if(haysize==0||haysize<needsize) return -1;        for(int i=0; i<haysize;i++){            int count=0;            while(count<needsize&&haystack[i+count]==needle[count]) count++;            if(count==needsize) return i;        }        return -1;    }

算法时间复杂度:O(n^2)

原创粉丝点击