Description:
Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:在一个字符串当中查找是否包含另一个字符串,如果包含就返回该位置的索引。利用一个嵌套循环遍历haystack即可。
class Solution {
public:
int strStr(string haystack, string needle) {
for(int i=0;;i++){
for(int j=0;;j++){
if(j==needle.length()){
return i;
}
if(i+j==haystack.length()){
return -1;
}
if(needle.charAt(j)!=haystack.charAt(i+j)){
break;
}
}
}
}
};