20170928宜信软件研发编程题:
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
1、使用string类中自定义函数:
使用字符串string自带查找函数find();find()查找的是字符串第一个字符,并 不是整个字符串,要判断是否取到短字符串的整个位置;
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1, str2;
while (cin >> str1 >> str2)
{
if (str1.empty() || str2.empty())
cout << -1;
if (str1.size() < str2.size())
{
string str;
str = str1;
str2 = str;
}
if (str1.find(str2) && str1[str1.find(str2)+str2.size()-1]==str2[str2.size()-1])
cout << str1.find(str2);
else
cout << -1;
}
return 0;
}
2、一般方法实现:
#include<iostream>
#include<string>
using namespace std;
int strStr(const char *source, const char *target) {
// write your code here
if (source == NULL || target == NULL) return -1;
int lenS = strlen(source);
int lenT = strlen(target);
for (int i = 0; i < lenS - lenT + 1; ++i)
{
int j;
for (j = 0; j < lenT; ++j)
{
if (source[i + j] != target[j])
break;
}
if (j == lenT) return i;
}
return -1;
}
int main()
{
char source[100] = {}, target[100]= {};
while (cin >> source >> target)
{
cout << strStr(source, target)<<endl;
}
return 0;
}
3、KMP算法:
还在学习中。。。