【问题标题】:Program to find the number of substrings that are palindromes in a given string查找给定字符串中回文子串的数量的程序
【发布时间】:2019-09-15 15:35:11
【问题描述】:

这是我的代码,但函数 countPalindromes 出于某种原因总是返回 0。我不明白为什么

bool isPalindrome(string s) {
    int x=0;
    int r= s.length() -1;
    while(r>1){
        if(s[x++]!=s[r--])
        {
            cout<<"Not Palindrome";
        }
        else
        {
            return true;
        }
    }
}

int countPalindromes(string s) {
    int n= s.length();
    int counter=0;
    for(int i = 0; i<n ;  i++)
    {
        for(int j=1; j< n -i ; j++)
        {
            if(isPalindrome(s.substr(i,j)=true))
            {
             counter+=1;
            }

        }

    }
    return counter;
}


int main() {
    cout<<countPalindromes("ABA");
    return 0;
}

【问题讨论】:

  • 您需要学习如何使用调试器逐步执行代码,这将帮助您找到自己的错误。也就是说,作为这里的新用户,请使用tour 并阅读How to Ask
  • 这里有一堆错误。使用调试器单步执行逻辑并确保它在每个点上都按照您的意愿行事。

标签: c++ string substring palindrome


【解决方案1】:

countPalindrome()isPalindrome() 函数都有很多错误。

  1. 首先在 isPalindrome() 函数中,检查直到 r>1。您必须检查整个字符串。为此,条件将是 r>=0。只要有字符匹配,您就会返回 true。在确定位置 S[i] 的任何字符不等于 S[n-i-1](其中 n 是字符串的长度)后,您可以返回 true。
  2. 其次是 countPalindromes() 函数,您在比较子字符串时传递了错误的参数。

看看你修改过的代码就明白了。

bool isPalindrome(string s) {
    int x=0;
    int r= s.length() -1;
    while(r>=0){
        if(s[x++]!=s[r--])
        {
            //cout<<"Not Palindrome"<<endl;
            return false;
        }
    }
    return true;
}

int countPalindromes(string s) {
    int n= s.length();
    int counter=0;
    for(int i = 0; i<n ;  i++)
    {
        for(int j=1; j<= n -i ; j++)
        {
            if(isPalindrome(s.substr(i,j))==true)
            {
             counter+=1;
            }

        }

    }
    return counter;
}


int main() {
    cout<<countPalindromes("ABA");
    return 0;
}

【讨论】:

  • 非常感谢,我现在明白了
猜你喜欢
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多