字符串移位包含的问题

两种思考方法:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值