题目
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路
可以利用C++的关于string的函数。
截取字符串:string.substr(i, len);
比较字符串是否以后者开头:strcmp(allstring.c_str(), prefix.c_str());
代码
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle=="") {
return 0;
}
for (int i=0; i<haystack.size(); i++) {
string hay = haystack.substr(i, needle.size());
if (strcmp(hay.c_str(), needle.c_str()) == 0) {
return i;
}
}
return -1;
}
};