Leetcode 28. Implement strStr()
2018-01-02 11:13
429 查看
题目的意思是判断needle是否是haystack的子串,如果不是的话就返回-1,如果是的话就返回haystack中与needle匹配的子串的第一个字符的索引值。
方法1:遍历haystack,遇到与needle[0]相等的字符,就判断两个字符串接下来的needle.size()-1个字符是否匹配,匹配的话就返回haystack中第一个匹配字符的索引值。
class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0; ; ++i)
{
for (int j = 0; ; ++j)
{
if (j == needle.size())
return i;
if(i+j==haystack.size())
return -1;
if (haystack[j + i] != needle[j])
break;
}
}
}
};
方法2:用了substr。
方法1:遍历haystack,遇到与needle[0]相等的字符,就判断两个字符串接下来的needle.size()-1个字符是否匹配,匹配的话就返回haystack中第一个匹配字符的索引值。
class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0; ; ++i)
{
for (int j = 0; ; ++j)
{
if (j == needle.size())
return i;
if(i+j==haystack.size())
return -1;
if (haystack[j + i] != needle[j])
break;
}
}
}
};
方法2:用了substr。
class Solution { public: int strStr(string haystack, string needle) { if(needle.empty()) return 0; for(int i=0; i<haystack.size(); i++) { if(haystack.substr(i,needle.size())==needle) return i; } return -1; } };
相关文章推荐
- 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 - 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() KMP算法解题
- [LeetCode] 28. Implement strStr() ☆
- LeetCode28. Implement strStr()
- Leetcode -- 28. Implement strStr()