c++ - 算法按顺序查找回文的用户输入长度
问题描述
我通过阅读网站学习 C++ 已经有几个星期了,在章节摘要测验失败后,我决定在线尝试一些练习。我现在尝试了将近一天,在解决了很多事情之后,最终我遇到了瓶颈。在此代码的缩写版本中,试图在文本中手动查找用户输入的回文长度,它在这种情况下可以部分工作:例如:
用户输入:长度 - 3,序列 - 12321:
- 请求的回文是:2 3 2(按预期工作和打印)
用户输入:长度 - 3,序列 - 13122:
当前 I: 2 Ivec[i]: 3
当前 RI:2 Ivec[ri]:3 计数器:1
当前 I: 3 Ivec[i]: 1
^^这条线应该发生在这两种情况下(当ri = 3和I = 1时,但它只在我达到3时第二次发生)。
当前 RI:1 Ivec[ri]:1 计数器:2
- “没有这样的回文。”
std::cout << "Please enter a length: "; //Palindrome length to search in a vector
int K;
std::cin >> K;
std::cout << "Please enter a sequence:\n\n";
int temp = 0;
std::cin >> temp;
//function to get length of sequence
//loop to convert sequence to a vector of integers
bool found(false);
int counter = 0;
std::vector<int> cvec;
for(int i = 0; i < length; ++i)
{
for(int ri = length; ri >= 0; --ri)
{
if(ivec[i] == ivec[ri] && std::abs(ri - i) <= K)
{
if(ri == i && ivec[ri + 1] != ivec[i - 1])
// for example: 1 2 3 2 1 << (ri(3),i(2)) ignored but the rest works fine and gets added to cvec
++i;
else
{
cvec.push_back(ivec[ri]);
++counter;
std::cout << "current I: " << i << "\tIvec[i]: " << ivec[i] << '\n'
<< "current RI: " << ri << "\tIvec[ri]: " << ivec[ri] << '\n' << "counter: " << counter << std::endl;
// used for testing.
++i;
}
}
}
// if counter reach user length of Palindrome
if(counter == K)
{
found = true;
break;
}
}
// if found..
解决方案
推荐阅读
- python - 使用python拆分csv文件中的单列
- python - 列表列表的乘法
- ruby-on-rails - Rails 应用程序意外安装在根文件夹中
- c# - mscorlib.dll 中出现“System.FormatException”类型的未处理异常附加信息:输入字符串的格式不正确
- python - Keras Tokenizer 中词索引的长度
- binding - 使用 Aurelia Property Observer 忽略您自己的更改的最佳方法
- node.js - NPM 全局安装
- json - 使用 Swift JSON 从 TheMovieDB API 获取数据时遇到问题
- keycloak - Keycloak的请求错误中未提供客户端密码
- macos - Apple TextEdit,它的工具栏从何而来?