給你兩個(gè)字符串?haystack 和 needle ,請你在 haystack 字符串中找出 needle 字符串的第一個(gè)匹配項(xiàng)的下標(biāo)(下標(biāo)從 0 開始)。如果?needle 不是 haystack 的一部分,則返回??-1 。
示例 1:
輸入:haystack = "sadbutsad", needle = "sad"
輸出:0
解釋:"sad" 在下標(biāo) 0 和 6 處匹配。
第一個(gè)匹配項(xiàng)的下標(biāo)是 0 ,所以返回 0 。
示例 2:
輸入:haystack = "leetcode", needle = "leeto"
輸出:-1
解釋:"leeto" 沒有在 "leetcode" 中出現(xiàn),所以返回 -1 。
?
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 僅由小寫英文字符組成
void main() {
String haystack = "hello";
String needle = "ll";
print(strStr(haystack, needle));
}
int strStr(String haystack, String needle) {
if (haystack.length == 0 && needle.length == 0) {
return -1;
}
int temp = 0;
for (int i = 0; i < haystack.length; i++) {
if (haystack[i] != needle[temp]) {
i = i - temp;
temp = 0;
continue;
}
if (temp == needle.length - 1) {
return i - temp;
}
temp++;
}
return -1;
}
LeetCode28. 找出字符串中第一個(gè)匹配項(xiàng)的下標(biāo)文章來源:http://www.zghlxwxcb.cn/news/detail-472800.html
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。文章來源地址http://www.zghlxwxcb.cn/news/detail-472800.html
到了這里,關(guān)于LeetCode28. 找出字符串中第一個(gè)匹配項(xiàng)的下標(biāo)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!