您的位置:首页 > 其它

LeetCode 28. Implement strStr()

2017-05-24 15:06 344 查看
28. Implement strStr()

Description

Implement strStr().

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

Analysis

这道题的意思就是实现一个strstr函数。

这个函数的返回值是子字符串在字符串中首先出现的下标,若没有则返回-1。

我的做法是比较字符串与子字符串,看当前子字符串是否存在于字符串中。

一个一个匹配,当完全匹配后则返回当前下标减去子字符串长度得到结果。

否则结果返回-1。

Code

class Solution {
public:
int strStr(string haystack, string needle) {
int index ;
int len =haystack.size();
//len==0&&
if(needle.size()==0) return 0;
for(int i = 0 ; i <len;++i){
index = 1;
if(haystack[i] == needle[0]){
int j = 0;
for(j = i+1;j < len;++j){
if(index == needle.size() || haystack[j] != needle[index]){
break;
}
index ++;
}
if(index == needle.size()) return j - index;
}
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: