acm 试题 字符串排序

Given a string of letters(A-Z),your task is to arrange them in alphabetic order.
Following is an example:
A string "BAC" contains 3 letters B,A and C,you should output
ABC
ACB
BAC
BCA
CAB
CBA
In the output file.
A string may contain several letters same,for example "BBC" you should output like this:
BBC
BCB
CBB

Input

The first line of input contains a single integer t, the number of test cases,followed by the input data for each test data.Each test case is a string of n(1<=n<=26) letters.

Output

You should output Case K: in the first line and the sequences of arrangement in the following lines of each case.

Sample Input

2
BAC
BBC

Sample Output

Case 1:
ABC
ACB
BAC
BCA
CAB
CBA
Case 2:
BBC
BCB
CBB

 

这道题目,我采用的是递归算法实现的。 采用的链串&nbsp;结构;
算法简单描述为:对一个链串,有个标记开始置换的指针,然后向后移动,直到末尾,然后置换的指针前移,重复上面的过程。如果标记的指针的内容和移动指针内容不同就打印出来;

源代码如下:

#include <stdio.h>
#include <iostream>
using namespace std ;


typedef struct str
 {
    char ch ;
    struct str * next ;
}str ;


void print(str * s); //打印
void create(str *&s);//建立
void travel(str *&s,str * r) ;//遍历,采用递归算法,实现排列问题
void swap(char &a , char & b) ;//交换


int main(int argc, char* argv[])
 {
    str * s ;
    create(s);
   
    print(s);
    travel(s,s->next);
   
    system("PAUSE");
    return 0;
}


void create(str *&s)//建立链串
 {
    s = new str ;
   
    str * p ;
    str * q = s ;
    char ch ;
   
    while((ch = getchar())!= '/n')
     {
        p = new str ;
        p->ch  = ch ;
        p->next = NULL ;
       
        q->next = p ;
        q = p ;
    }
   
    q->next = NULL ;
}


void print(str * s)
 {
    str * p ;
    p = s->next ;
    while(p != NULL)
     {
        cout<<p->ch ;
        p = p->next ;
    }
   
    putchar('/n');
}


void swap(char &a , char & b)
 {
    char temp ;
    temp = a ;
    a = b ;
    b = temp ;
}

 


void travel(str *&s,str * r) //遍历
 {
   
    str * p = r;
    str * q = p->next ;

    if(r->next == NULL)
     {
        return ;
    }

    else
     {
        while(p!= NULL)
         {
            q = p->next ;
            while(q != NULL)
             {
                swap(p->ch,q->ch);
                if(p->ch != q->ch)
                 {
                    print(s);
                    travel(s,p->next);
                }
               
                swap(p->ch,q->ch);
                q= q->next ;
            }
            p = p->next ;
           
        }
    }

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值