Question:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路:
返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回-1。
利用substr依次比较,没什么说的。
注意substr(i,n)的含义是返回一个 从string[i]开始取长度为n 的string类型变量,而不是从i到n,之前理解有误。
Code:
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size()<needle.size())
return -1;
int x = -1;
int n = needle.size();
for(int i =0;i <= (haystack.size()-n);i++){
if(haystack.substr(i,n) == needle){
x = i;
break;
}
}
return x;
}
};