您的位置:首页 > 其它

八十第五个冠军(复制和匹配的字符串)

2015-07-10 08:53 423 查看
85.又见字符串问题

1.给出一个函数来复制两个字符串A 和B。

串A 经过几个字节和字符串B 重叠的前几个字节。

2.已知一个字符串,比方asderwsde,寻找当中的一个子字符串比方sde 的个数,假设没有返回0。有的话返回子字符串的个数。

思路:

1.遍历字符串A中的字符,和B中的第一个字符比較。若不同样则拷贝到目的字符串strDest中,若同样则有两种可能。一种是到达了AB重合部分的起始处,一种是恰巧同样,须要做出推断。採用依次比較的方法。从此处遍历到A字符串结尾处。若一直同样则说明是第一种情况,通过sameNum记录重合部分的个数。若在到达A字符串结尾之前出现了不同样的情况。说明是另外一种情况,把同样部分的字符拷贝到strDest中,并从下一个字符处继续运行该算法循环,详细实现參考代码。

2.基于KMP字符串匹配算法,通过matchNum记录匹配次数,每次匹配成功后。matchNum++,并从匹配起始位置的下一个位置開始又一次运行匹配算法,直到源字符串结束。

#include "stdafx.h"
#include<iostream>
using namespace std;
namespace MS100P_85
{
void copyStr(const char* A, const char* B, char* strDest)
{
int i = 0;
int j = 0;
int sameNum = 0;	//A尾部和B头部匹配上的字符个数
while (A[i] != '\0')
{
while (A[i] != B[0] && A[i] != '\0')	//复制直到同样遇到字符
{
strDest[i] = A[i++];
}
if (A[i] == '\0')
sameNum = 0;
else
{
while (A[i + j] == B[j] && A[i + j] != '\0')	//推断同样字符能否够一直匹配到A结束
j++;
if (A[i + j] == '\0')	//若能够。记录匹配个数,跳出循环
{
sameNum = j;
while (A[i] != '\0')
{
strDest[i] = A[i];
i++;
}

}
else                      //否则,复制当前字符,前进一个位置。继续运行
{
strDest[i] = A[i++];
j = 0;
}
}
}
for (j = sameNum; B[j] != '\0'; j++)
strDest[i++] = B[j];
strDest[i] = '\0';
}

void getNext(int next[], const char* t)
{
int k = -1;
next[0] = -1;
int j = 0;
int len = strlen(t);
while (j < len - 1)
{
if (k == -1 || t[j] == t[k])
{
if (t[++j] == t[++k])
next[j] = next[k];
else
next[j] = k;
}
else
k = next[k];
}
}

int KMP(const char* s,const char* t)
{
int matchNum = 0;
int len1 = strlen(s);
int len2 = strlen(t);
int *next = new int[len2];
getNext(next, t);
int i = 0, j = 0;
while (i<len1)
{
while (i<len1&&j<len2)
{
if (j == -1 || s[i] == t[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j==len2)
{
//return i-j;
i = i - j + 1;
j = 0;
matchNum++;
}
}
return matchNum;
}

void test()
{
const char* A = "ranshao";
const char* B = "shaoqiang";
char* strDest = new char[strlen(A) + strlen(B) + 1];
cout << A << endl;
cout << B << endl;
copyStr(A, B, strDest);
cout << "result of copy is: " << strDest << endl;
delete[] strDest;

const char* s = "asderwsde3rsde";
const char* t = "sde";

cout << s << "  has  "<< KMP(s, t) <<" "<<t<<endl;
}

}
int _tmain(int argc, _TCHAR* argv[])
{
MS100P_85::test();
return 0;
}


执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: