首页 > 解决方案 > 算法按顺序查找回文的用户输入长度

问题描述

我通过阅读网站学习 C++ 已经有几个星期了,在章节摘要测验失败后,我决定在线尝试一些练习。我现在尝试了将近一天,在解决了很多事情之后,最终我遇到了瓶颈。在此代码的缩写版本中,试图在文本中手动查找用户输入的回文长度,它在这种情况下可以部分工作:例如:

用户输入:长度 - 3,序列 - 12321:

用户输入:长度 - 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..

标签: c++algorithmmath

解决方案


推荐阅读