题目:
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
来源:力扣(LeetCode)
思路:
双指针思想(感觉双指针的用处好多,有待发掘)。一个指针指向数组,从0开始;另一个指针指向待查找的数组。如果两个指针指向的内容不一致,则i+1;若一致,则j+1,继续比较i+j和j指针的内容。
class Solution {
public:
int strStr(string haystack, string needle) {
int i,j; //两个指针
int n = haystack.length();
int m = needle.length();
for(i = 0;i < n-m+1;i++){
for(j = 0; j < m;j++){
if(haystack[i + j] != needle[j]){
break;
}
}
if(j == m){return i;}
}
return -1;
}
};