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
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; } };
相关文章推荐
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- Leetcode 28. Implement strStr()
- [Leetcode]28. Implement strStr()
- [leetcode]28. Implement strStr()
- LeetCode28. Implement strStr()
- [LeetCode] 28. Implement strStr() ☆
- leetcode刷题记录-28. Implement strStr()
- leetcode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- Leetcode -- 28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- LeetCode_Easy心得:28. Implement strStr()(C语言)
- leetcode:28. Implement strStr()
- LeetCode 28. Implement strStr()
- leetcode 28. Implement strStr() 三种解法
- 【一天一道LeetCode】#28. Implement strStr()
- Leetcode28. Implement strStr()
- LeetCode 28. Implement strStr()