2
我想按字典顺序重复打印所有排列的字符串。我写这篇文章的代码:重复打印排序排列
char *input;
void swap(char *x, char *y);
void permute(char *str);
int factorial(int n);
void swapSort(char array[], int left, int right);
void quick_sort(char *array, int left, int right);
//void permute(char *str, char *p_ch, int length);
int main() {
input = malloc(8 + 1 * sizeof(char));
fgets(input, 9, stdin);
int n = strlen(input);
if (input[n - 1] == '\n') {
n--;
input[n] = '\0';
}
printf("Length of string: %d\n", n);
printf("Input string: \"%s\"\n", input);
quick_sort(input, 0, n);
printf("sorted string: \"%s\"\n", input);
printf("Number of permutations: %d\n", factorial(n));
permute(input);
//free(input);
return 0;
}
int factorial(int n) {
if (n == 1) return 1;
return n * factorial(n - 1);
}
int compare(const void *a, const void *b) {
return (*(char *) a - *(char *) b);
}
void permute(char *str) {
int strSize = strlen(str);
qsort(str, strSize, sizeof(char), compare);
int endIsNotReached = true;
int tmpSize;
while (endIsNotReached) {
printf("\"%s\"\n", str);
for (tmpSize = strSize - 2; tmpSize > -1 && str[tmpSize] >= str[tmpSize + 1]; tmpSize--) {
//do nothing
}
if (tmpSize > -1) {
int j = 1 + tmpSize;
for (int index = j; index < strSize && str[index]; index++) {
if (str[index] < str[j] && str[index] > str[tmpSize])
j = index;
}
swap(&str[tmpSize], &str[j]);
qsort(str + tmpSize + 1, strSize - 1 - tmpSize, sizeof(char), compare);
}
else {
endIsNotReached = false;
}
};
}
void quick_sort(char *array, int left, int right) {
if (left < right) {
int boundary = left;
for (int i = left + 1; i < right; i++) {
if (array[i] < array[left]) {
swapSort(array, i, ++boundary);
}
}
swapSort(array, left, boundary);
quick_sort(array, left, boundary);
quick_sort(array, boundary + 1, right);
}
}
void swapSort(char array[], int left, int right) {
char tmp = array[right];
array[right] = array[left];
array[left] = tmp;
}
void swap(char *left, char *right) {
char temp = *left;
*left = *right;
*right = temp;
}
但是当我要打印字符串“AAA”输出仅仅是“AAA”,但我想有输出,其中为“AAA”的三倍。 (另一例 - 输入 - “AAB” - 输出 - “AAB”, “AAB”, “ABA”, “ABA”, “BAA”, “BAA”)
@MohitJain如何将它会是什么样子?我从来没有见过像 – prone666
@MohitJain之类的东西,因为我只能用C工作,而不用C++ – prone666
对不起,我的无知。你仍然可以在每个角色上使用一些标记来区分类似的角色。 –