题目描述:
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
例如:
如果 source = “source” 和 target = “target”,返回 -1。
如果 source = “abcdabcdefg” 和 target = “bcd”,返回 1。
解析:
字符串查找函数,strstr()函数用来检索子串在字符串中首次出现的位置,其原型为:char strstr( char *str, char substr );
思路:暴力求解
假设原字符串的长度是n,匹配串的长度是m。思路很简单,就是对原字符串的每一个长度为m的字串都判断是否跟匹配串一致。总共有n-m个子串,所以算法时间复杂度为O((n-m)*m)=O(n*m),空间复杂度是O(1)。
代码:
#include<iostream>
#include<string>
using namespace std;
int strStr(const string &source, const string &target)
{
if( source.length() == 0 || target.length() ==0)
return -1;
int n = source.length();
int m = target.length();
int i, j;
if(n < m)
return -1;
for(i = 0; i < n-m+1; i++)
{
for(j = 0; j < m; j++)
{
if(source[i+j] != target[j])
{
break;
}
}
if(j == m)
{
return i;
}
}
return -1;
}
int main()
{
string str1 = "abcdabkdefg";
string str2 = "bcd";
string str3 = "abk";
cout << strStr(str1, str2) << endl;
cout << strStr(str1, str3) << endl;
system("pause");
return 0;
}