28 . 找出字符串中第一個匹配項的下標(簡單)
方法:雙指針法
思路
-
使用 find 函數(shù)枚舉原串 ss 中的每個字符作為「發(fā)起點」,每次從原串的「發(fā)起點」和匹配串的「首位」開始嘗試匹配:文章來源:http://www.zghlxwxcb.cn/news/detail-683870.html
匹配成功:返回本次匹配的原串「發(fā)起點」。
匹配失敗:枚舉原串的下一個「發(fā)起點」,重新嘗試匹配。文章來源地址http://www.zghlxwxcb.cn/news/detail-683870.html
代碼
class Solution {
public:
int strStr(string haystack, string needle) {
int pos = haystack.find(needle[0]);
while(pos != -1) {
int p = pos, q = 0;
while(q<needle.size() && haystack[p] == needle[q]){
p++, q++;
}
// 已經(jīng)將needle遍歷完畢,說明匹配成功
if(q == needle.size()) return pos;
else {
// 將先前匹配的字符置'0',防止重復匹配
haystack[pos] = '0';
// 尋找下一個可能匹配的位置
pos = haystack.find(needle[0]);
}
}
return pos;
}
};
到了這里,關于【LeetCode】28 . 找出字符串中第一個匹配項的下標的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!