两种思考方法:
1、和正常的字符串比较没有什么区别,只是比较到数组的末尾时,需要从头开始在比较,也就是说如果超出数组的长度时,取一下模可以得到正确的坐标,继续比较就可以了。
2、将数组复制一边,再在复制后的数据上查找目标字符串。
代码如下:
#include <stdio.h>
#include <string>
bool RotateFind(const std::string& src, const std::string& target) {
std::string extend_src = src;
extend_src += src;
if (extend_src.find(target) != std::string::npos) {
return true;
} else {
return false;
}
}
bool RotateFind1(const std::string& src, const std::string& target) {
if (target.size() < 1) {
return false;
}
std::string head;
head += target[0];
int index = -1;
size_t src_index;
size_t target_index = 1;
while ((index = src.find(head, index + 1)) != std::string::npos) {
while (target_index < target.size()) {
src_index = (target_index + index) % src.size();
if (src[src_index] == target[target_index]) {
target_index++;
} else {
break;
}
}
if (target_index == target.size()) {
return true;
}
}
return false;
}
int main(int argc, char** argv) {
std::string src = "aabcd";
std::string target = "bcda";
if (RotateFind1(src, target)) {
printf("find\n");
} else {
printf("not find\n");
}
}
参考文献
编程之美3.1