#include <iostream>
using namespace std;
//反序字符串chs到字符串rchs.
//参数:chs[]原字符串, rchs[]目的字符串, len 长度
inline void reverse(const char chs[], char rchs[], int len){
int rindex = len;
for(int i=0; i < len; ++i){
rchs[--rindex] = chs[i];
}
rchs[len] = '/0';
}
//获取临时字符串, 放置于temp 中.
//参数: temp 临时字符串, chs 原字符串, offset 偏移量, 0-(len-1), len temp字符串长度
inline void getChs(char temp[], const char chs[], int offset, int len){
int temp_index = -1;
for(int i = 0; i < len; ++i){
temp[++temp_index] = chs[offset + i];
}
temp[len] = '/0';
cout << "the temp: " << temp << endl;
}
//验证字符串temp 是否存在于字符串rchs 中. 存在返回ture, 否则返回false
//参数: temp 临时字符串, rchs 被检验是否包含temp的字符串, len temp字符串长度, limit 限制rchs被检验的字符数
inline bool compare(const char temp[], const char rchs[],int len, int limit){
int ii = 0; //rchs被检验的字符索引
int offset = 0; //temp中的偏移量, 每次匹配重置
bool first = false; //是否匹配temp第一个字符标示.
// if(strcmp(temp,"sabcd")==0){
// cout << "len :: " << strlen(temp) << endl;
// }
while(ii < limit && offset < len){//当检索到限制数目 或已经在rchs中匹配temp, 循环结束
if(!first){
if(temp[0] == rchs[ii]){
first = true; //匹配temp第一个字符
offset = 1; //偏移量设置为第二个字符.
}
}else{
if(temp[offset++] != rchs[ii]){ //检验单个字符是否匹配
first = false; //重新匹配temp 第一个字符标示
offset = 0; //重置偏移量为0
}
}
++ii;
}
if(offset == len){ //匹配成功
cout << "the result: " << temp << endl;
return true;
}
else
return false;
}
int main(){
char chs[] = "fesabcdsfsfdcbasf";
const int len = strlen(chs);
cout << "len: " << len << endl;
char rchs[len + 1];
//反序
reverse(chs, rchs, len);
cout << chs << endl;
cout << rchs << endl;
int middle = len/2;
bool flag = true;
for(int i = middle; i > 0 && flag; --i ){
for(int j=0; j <= (middle - i) && flag; ++j){
char temp[len + 1];
getChs(temp, chs, j , i);
//flag = compare("sabc", "asabccccc", 4, 5);
flag = !compare(temp, rchs, i, len - middle);
}
}
system("pause");
return 1;
}
这个例子是 在某个字符串chs 中正序字符串S及其反序字符串SR并存的情况下, 求其中最大的正序字符串.
思路: 1. 如字符串chs= 'fesabcdsfsfdcbasf", 其反序字符串rchs = "fsabcdfsfsdcbasef";
2. 由于s 和 sr 是不覆盖的, 所以取 chs 前部分去匹配rchs 的前部分就行了;
3. chs 的长度是17, 所以最多取前8 个字符串跟 rchs 匹配就行了, 只匹配 rchs 前(17-8) 个字符串.
4. the temp: fesabcds
the temp: fesabcd
the temp: esabcds
the temp: fesabc
the temp: esabcd
the temp: sabcds
以此类推, 逐渐减少匹配字符串的长度, 直到成功匹配.