【Leetcode】之Implement strStr()

来源:互联网 发布:网络设计方案 编辑:程序博客网 时间:2024/05/18 11:46

一.问题描述

Implement strStr().

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

二.我的解题思路

这道题目也比较简单,使用简单的双指针比较即可。注意为了提高时间效率,在程序的开头可以对两个字符串的length先进行一个初步的比较。测试通过的程序如下所示:

class Solution {public:    int strStr(string haystack, string needle) {        int len=haystack.length();int candidate=-1;        int need = 0;int ned_len=needle.length();        if(len<ned_len) return -1;        if(len==ned_len)        {            for(int i=0;i<len;i++){            if(haystack[i]!=needle[i]) return -1;            }            return 0;        }        if(len==0 || ned_len==0) return 0;        for(int i=0;i<len;i++){            if(haystack[i]==needle[need]){                candidate=i;                while( i<len && need<ned_len){                    if(haystack[i]!=needle[need]) break;                    else {i++;need++;}                }                if(need==ned_len && (haystack[i-1]==needle[need-1])) return candidate;                else {                    need=0;                    i=candidate;                    candidate=-1;                }            }        }        return candidate;    }};
0 0
原创粉丝点击