【问题标题】:Using next_permutation to get palindrome string使用 next_permutation 获取回文字符串
【发布时间】:2015-07-25 05:24:31
【问题描述】:

我正在尝试制作一个程序来尝试字符串中的每个排列以检查它是否可以创建回文字符串。如果不是,它会删除一个字符并再次尝试,依此类推,直到找到解决方案。我不明白为什么它会给我一个分段错误。这是我的代码:

bool IsPalindrome(string s){
string t;
int x=s.size()-1;
for(int i=x;i>=0;i--)
    t+=s[i];

 if(s==t)
     return true;
 else
     return false;
}

void generate_permutation(string s,int i){
 sort(s.begin(),s.end());
do{
if(IsPalindrome(s)){
    if(i%2==0){
        cout<<"First"<<endl;
        exit(0);
    }
    else{
        cout<<"Second"<<endl;
        exit(0);
       }
   }

}while(next_permutation(s.begin(),s.end())) ;


 }


int main(){


string s;
cin>>s;
int i=0;
while(s.size()>=1){
generate_permutation(s,i);
s.erase(s.begin()+i);
i++;
   }



}

【问题讨论】:

  • 你的问题是什么
  • 你不需要尝试所有的排列;只需确保您对每个唯一字符都有一个偶数计数(以及可选的一个具有奇数计数的唯一字符)。
  • if (foo) return true; else return false; 是多余的,在布尔上下文中等同于 return foo;。

标签: c++ permutation


【解决方案1】:
int i=0;
while(s.size()>=1){ // size() goes down to 1
generate_permutation(s,i);
s.erase(s.begin()+i); // the i'th element is always the one erased
i++; // i goes up and up

也许您打算删除第一个或最后一个字符,而不是第一个,然后是第二个,然后是第三个......

【讨论】:

  • yesh 解决了这个问题,并且 cmets 非常有用,谢谢。
【解决方案2】:

这可能就是你想要的

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    for (cin >> s; s.size(); ) {
        sort(s.begin(), s.end());
        do {
            if (equal(s.begin(), s.end(), s.rbegin())) {    // Palindrome check
                cout << s << endl;
                return 0;
            }
        } while (next_permutation(s.begin(), s.end()));    // all permutations
        string::iterator it = unique(s.begin(), s.end(), [](char a, char b) {
                return a != b;
            });    // first non repeating char
        s.erase(it != s.end() ? it : s.begin());    // erase a char
    }
    return 0;
}

示例输入

abaca

样本输出

aaa

查看演示http://ideone.com/VgTEgS。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2019-07-22
    • 2011-12-06
    相关资源
    最近更新 更多