title: 每日一練(37):實(shí)現(xiàn) strStr()
categories:[劍指offer]
tags:[每日一練]
date: 2022/03/21
每日一練(37):實(shí)現(xiàn) strStr()
實(shí)現(xiàn) strStr() 函數(shù)。
給你兩個(gè)字符串 haystack 和 needle ,請(qǐng)你在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個(gè)位置(下標(biāo)從 0 開始)。如果不存在,則返回 -1 。
說明:
當(dāng) needle 是空字符串時(shí),我們應(yīng)當(dāng)返回什么值呢?這是一個(gè)在面試中很好的問題。
對(duì)于本題而言,當(dāng) needle 是空字符串時(shí)我們應(yīng)當(dāng)返回 0 。這與 C 語(yǔ)言的 strstr() 以及 Java 的 indexOf() 定義相符。
示例 1:
輸入:haystack = "hello", needle = "ll"
輸出:2
示例 2:
輸入:haystack = "aaaaa", needle = "bba"
輸出:-1
示例 3:
輸入:haystack = "", needle = ""
輸出:0
提示:
0 <= haystack.length, needle.length <= 5 * 104
haystack 和 needle 僅由小寫英文字符組成
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-strstr
方法一:雙指針法(暴力解法)
思路分析
判斷是否相等,同步往后移
不相等退回開始的位置,i+1,j=0;
int strStr(string haystack, string needle) {
int i = 0;
int j = 0;
while (haystack[i] != '\0' && needle[j] != '\0') {
if (needle[j] == haystack[i]) {//判斷是否相等
j++;
i++;
} else { //不相等退回開始的位置,i+1,j=0;
i = i - j + 1;
j = 0;
}
}
if (j == needle.length()) { //j為步長(zhǎng)
return i-j;
}
return -1;
}
方法二:find函數(shù)
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
return haystack.find(needle);
}