實現 strStr() 函式,長字串裡搜短字串
阿新 • • 發佈:2021-02-12
技術標籤:C++從零開始
給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
輸入: haystack = "hello", needle = "ll"
輸出: 2
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-strstr
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
思路:
1、比較長度,分類討論
2、遍歷長字串,每當遇見短字串第一個,查一次
程式碼
int strStr(string haystack, string needle) {
int len1 = haystack.length();
int len2 = needle.length();
// haystack比needle短,必然失敗
if(len1<len2){
return -1;
}
// haystack和needle一樣長,直接比較是否相同
if (len2==0){
return 0;
}
if(len1==len2){
if(haystack==needle){
return 0;
}else{
return -1;
}
}
// haystack比needle長,遍歷haystack,每次發現needle的第一個字元,就查一次
int label = 0;
for(int j=0;j<= len1-len2;j++){
label = 0;
if (haystack[j] == needle[0]){
for(int i=0;i<len2;i++){
if(haystack[j+i]!=needle[i]){
label = -1;
}
}
if(label == 0){
return j;
}
}
}
return -1;
}