获取输入字符串的下一个字典序排列

如输入是ABEDGFC
则下一个字典序排列为ABEFCDG
算法流程:
1.从后往前遍历字符串str,找到第一个str[i]满足str[i]小于str[i+1],样例中,str[i]=D。此时,子序列GFC已经为字典序的最后一个排列。
2.从后往前遍历字符串str,找到第一个str[j]满足str[j]>str[i],样例中str[j]=F。
3.交换str[i]与str[j],得到ABEFGDC,并把i之后的字符串逆序,得到ABEFCDG,即为所求。
程序如下:

//
//  FindeNext.cpp
//  STL
//  寻找下一个字典序排列
//  Created by 林和睿 on 15/9/18.
//  Copyright (c) 2015年 林和睿. All rights reserved.
//

#include <stdio.h>
#include <iostream>
using namespace std;
char* findnext(char *current,int length){
    if(current==NULL) return NULL;
    int i = length-2;
    while(current[i]>current[i+1]){//从后往前找到第一个str[i]<str[i+1]
        i--;
        if(i<0) return NULL;
    }
    char tmp;
    int j = length-1;
    for(;j>i;j--){
        if(current[j]>current[i]){//从后往前找到第一个大于str[i]的str[j],交换str[i]和str[j]
            tmp = current[j];
            current[j] = current[i];
            current[i] = tmp;
            break;
        }
    }
    //把i之后的字符串倒序
    j=length-1;
    i = i+1;
    while(i<j){
        char tmp = current[j];
        current[j] = current[i];
        current[i] = tmp;
        i++;j--;
    }
    return current;
}

int main(){
    string q("ABEDGFC");
    char* w = const_cast<char*>(q.data());
    char *p = findnext(w,7);
    cout<<p<<endl;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值