在c ++中找到一个字符串的所有排列 [英] find all permutations of a string in c++

查看:83
本文介绍了在c ++中找到一个字符串的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是打印给定字符串的所有排列的代码。

The following is a code to print all permutations of a given string. The code compiles but does not print anything.

using namespace std;

void RecPermute(string, string);

int main() {
    RecPermute("", "abc");
    return 0;
}

void RecPermute(string soFar, string rest) {
    if (rest == " ") {
        cout << soFar << endl;
    } else {
        for(int i=0; i<rest.length(); i++) {
            string next = soFar + rest[i];
            string remaining = rest.substr(0, i) + rest.substr(i+1);
            RecPermute(next, remaining);
    }
    }
}

需要修复什么?

推荐答案

所以你这么诱人的接近。你只需要当空字符串匹配而不是一个空格。您可以通过匹配空字符串来执行此操作。

So you are so tantalizingly close. You just want when the empty string is matched as opposed to a space. You can do this by matching the empty string "".

更改

if (rest == " ") { ... }

if (rest == "") { ... }

,并且忘记了rest.substr(i + 1)的长度,它应该是(i + 1,i-3 );

and you forgot the length of rest.substr(i+1), it should be (i+1,i-3);

这篇关于在c ++中找到一个字符串的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆