剑指offer—字符串的排列

来源:互联网 发布:刀哥swift3.0源码 编辑:程序博客网 时间:2024/05/16 20:30

华电北风吹
天津大学认知计算与应用重点实验室
日期:2015/10/4

题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

解析:每次寻找一个比当前字符串大1的字符串。规则很好找从最后一位寻找,若前一位比当前位大,往前移一位,知道发现有比当前位小的停止(若没发现,当前字符串已是最大,算法退出),然后在末尾这些排好序的字符中寻找比这个字符串大的最小的哪个放到这个字符串的位置,把剩下的字符串从小到大接到后面即可。
利用algorithm库里面的next_permutation函数。

class Solution {public:    vector<string> Permutation(string str)    {        vector<string> result;        if (str == "")            return result;        sort(str.begin(), str.end());        result.push_back(str);        while (next_permutation(str.begin(),str.end()))        {            result.push_back(str);        }        return result;    }};

自己写代码实现

class Solution {public:    vector<string> Permutation(string str)    {        vector<string> result;        if (str == "")            return result;        sort(str.begin(), str.end());        result.push_back(str);        if(str.length()==1)            return result;        while (Next(str))        {            result.push_back(str);        }        return result;    }    bool Next(string &str)    {        int length = str.length();        int i = length - 2;        while (i > 0 && str[i] >= str[i + 1])        {            i--;        }        if ((i == 0) && (str[i] >= str[i + 1]))            return false;        int j = length - 1;        while (str[j] <= str[i])        {            j--;        }        string temp = str;        str[i] = temp[j];        temp[j] = temp[i];        for (int k = i + 1; k < length; k++)            str[k] = temp[length - k + i];        return true;    }};
0 0