題目描述:實作 strStr() 函數。
給定一個 haystack 字元串和一個 needle 字元串,在 haystack 字元串中找出 needle 字元串出現的第一個位置 (從0開始)
輸入示例1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
輸入示例2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
算法思想:
方法1:暴力法求解,從母字元串的第一個位置開始截取子字元串長度的子字元串,然後比較兩個字元串是否相等。
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle=="")
return 0;
int len1=haystack.size();
int len2=needle.size();
bool flag=false;
for(int i=0;i<len1-len2+1;i++){
string subs=haystack.substr(i,len2);
if(subs.compare(needle)==0)
return i;
}
return -1;
}
};
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
int pos=haystack.find(needle);
return pos;
}
};