本博文参照 第九题:(1)设计Strcmp(s,t)算法,实现两个字符串s和t的比较(2)设计一个算法,在字符串str中查找子串substr最后一次出现的位置 进行总结归纳,如有需要,可以自行查看原文。
- 设计Strcmp(s,t)算法,实现两个字符串s和t的比较
首先判断两个字符串的长度是否相同,不相同则返回1和-1,并结束比较;否则,逐个字符依次比较,当所有字符均相同时返回1,否则根据字符的asclli码表比较,返回1或者-1。 - 设计一个算法,在字符串str中查找子串substr最后一次出现的位置
方法1:使用朴素的模式匹配算法,逐个字符依次比较,找到子串substr出现在字符串str中的每个位置,取最后一次的位置即可。
方法2:使用KMP算法,仍然是调用多次kmp算法,找到substr出现在str中的每个位置,取最后一次的位置作为最后的结果。
#include<iostream>
#include<cstring>
using namespace std;
int Strcmp(string s,string t){
int slen = s.length();
int tlen = t.length();
int ss = 0,tt = 0;
while(ss<slen&&tt <tlen){
if(s[ss]>t[tt])
return 1;
if(s[ss]<t[tt])
return -1;
if(s[ss]==t[tt]){
ss += 1;
tt += 1;
}
}
if(slen > tlen)
return 1;
if(slen < tlen)
return -1;
if(slen==tlen)
return 0;
}
void Next(string s,int* next){
int i = 0,j = 1;
next[0] = 0;
while(j < s.length()){
if(s[i] == s[j]){
next[j] = next[j-1]+1;
j += 1;
i += 1;
}
else{
if(i == 0){
next[j] = 0;
j += 1;
}
if(i != 0)
i = next[i - 1];
}
}
}
int KMP(string str,string subst){
int i = 0,j = 0,pos = -1;
int* next = new int[subst.length()];
Next(subst,next);
for(int m = 0;m < subst.length();m++)
cout << next[m] << " ";
while(i < str.length()){
if(str[i] == subst[j]){
if( j == subst.length()-1){
pos = i -j;
j = 0;
i += 1;
}
else{
i += 1;
j += 1;
}
}
else{
if(j!= 0)
j = next[j];
else
i += 1;
}
}
return pos;
}
int main(){
string s,t;
cout << "Input S:" ;
cin >> s;
cout << endl << "Input T:" ;
cin >> t;
int i = Strcmp(s,t);
switch(i){
case 1:
cout << endl << "S > T" << endl;
break;
case -1:
cout << endl << "S < T" << endl;
break;
case 0:
cout << endl << "S = T" << endl;
break;
}
string str,subst;
cout << endl << "Input str:";
cin >> str;
cout << endl << "Input substr:" ;
cin >> subst;
int pos = KMP(str,subst);
if(pos == -1)
cout << endl << "str 不是 substr 的子串" << endl;
else
cout << endl <<"str 在 substr 中最后一次出现的位置为:" << pos << endl;
return 0;
}