Description:
-
Enter a string and print all characters in the string in lexicographically. For example, if abc is input, all the strings abc, acb, bac, bca, cab, and CBA that can be arranged by characters a, B, and c are printed.
-
Input:
-
Each test case contains one line.
Enter a string of no more than 9 characters (repeated characters may exist), including only uppercase and lowercase letters.
-
Output:
-
All data groups are output in Lexicographic Order.
-
Sample input:
abcBCA
-
Sample output:
abcacbbacbcacabcbaABCACBBACBCACABCBA
Solution:
Pay attention to two issues for this question:
The first one isDuplicate letterAnd the second isIn alphabetical order.
Duplicate letters can be skipped directly during the exchange. In the dictionary order, we need to arrange them.
Sort by bubble:
void bubbleSort(char *arr,int begin,int length){ int i,j; for(i=begin;i<length;i++){ for(j=i+1;j<length;j++){ if(arr[i]>arr[j]){ swap(&arr[i],&arr[j]); } } }}
When switching, ignore repeated character exchanges:
void Permulation(char *arr,int k,int length){ int i; if(k == length){ for(i=0;i<length;i++) printf("%c",arr[i]); printf("\n"); }else{ for(i=k;i<length;i++){ if(k != i && arr[k] == arr[i]) continue; swap(&arr[k],&arr[i]); bubbleSort(arr,k+1,length); Permulation(arr,k+1,length); bubbleSort(arr,k+1,length); } }}
After each exchange, the remaining elements are arranged once. For example, the string abc is changed to CBA during the last outer exchange.
In this case, sort the cab and sort it.
All code:
#include <stdio.h>#include <stdlib.h>#include <string.h>void bubbleSort(char *arr,int begin,int length);void swap(char *a,char *b);void Permulation(char *arr,int k,int length); int main(){ char arr[10]; int length; int i; while(gets(arr)){ length = strlen(arr); bubbleSort(arr,0,length); Permulation(arr,0,length); } return 0;}void Permulation(char *arr,int k,int length){ int i; if(k == length){ for(i=0;i<length;i++) printf("%c",arr[i]); printf("\n"); }else{ for(i=k;i<length;i++){ if(k != i && arr[k] == arr[i]) continue; swap(&arr[k],&arr[i]); bubbleSort(arr,k+1,length); Permulation(arr,k+1,length); bubbleSort(arr,k+1,length); } }}void swap(char *a,char *b){ char c; c = *b; *b = *a; *a = c;}void bubbleSort(char *arr,int begin,int length){ int i,j; for(i=begin;i<length;i++){ for(j=i+1;j<length;j++){ if(arr[i]>arr[j]){ swap(&arr[i],&arr[j]); } } }}/************************************************************** Problem: 1369 User: xhalo Language: C Result: Accepted Time:470 ms Memory:912 kb****************************************************************/