實現 strStr() 函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll" 輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba" 輸出: -1
說明:
當 needle
是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
class Solution {
public:
int strStr(string haystack, string needle) {
int m=haystack.size();int n=needle.size();
int i=0;int j=0;bool flat=true;int sign=0;
if(n<1) return 0;
if(m<1||m<n) return -1;
while(i<m&&j<n)
{
if(haystack[i]==needle[j])
{
flat=compare(haystack,needle,i);
if(flat)
{
sign=i;
return sign;
}
}
i++;
}
return -1;
}
bool compare(string s1,string s2,int i)
{
int h=s1.size();int k=s2.size();int it=1;int ix=i+1;
while(it<k)
{
if(s1[ix]==s2[it])
{
it++;
ix++;
continue;
}
else
return false;
}
return true;
}
};
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return 0;
int m = haystack.size(), n = needle.size();
if (m < n) return -1;
for (int i = 0; i <= m - n; ++i) {
int j = 0;
for (j = 0; j < n; ++j) {
if (haystack[i + j] != needle[j]) break;
}
if (j == n) return i;
}
return -1;
}
};
int main()
{
Solution temp;
string s1 = "hello";string s2 = "llt";
cout << temp.strStr(s1, s2) << endl;
system("pause");
return 0;
}