在C ++中打印重复的给定字符串的所有不同排列
在此问题中,我们给了一个可能包含重复字符的字符串。我们的任务是打印所有不同的字符串排列。
让我们以一个例子来了解问题-
Input: string = “XYZ” Output: XYZ XZY YXZ YZX ZYX ZXY
为了解决这个问题,我们必须修复字符串的一个元素。然后迭代字符串的所有元素。
示例
实施我们的解决方案的程序,
#include <string.h>
#include <iostream>
using namespace std;
int compare(const void* a, const void* b) {
return (*(char*)a - *(char*)b);
}
void swapChar(char* a, char* b) {
char t = *a;
*a = *b;
*b = t;
}
int findCeil(char str[], char first, int l, int h) {
int ceilIndex = l;
for (int i = l + 1; i <= h; i++)
if (str[i] > first && str[i] < str[ceilIndex])
ceilIndex = i;
return ceilIndex;
}
void printPermutations(char str[]) {
int size = strlen(str);
qsort(str, size, sizeof(str[0]), compare);
bool isFinished = false;
while (!isFinished) {
static int x = 1;
cout<<str<<"\t";
int i;
for (i = size - 2; i >= 0; --i)
if (str[i] < str[i + 1])
break;
if (i == -1)
isFinished = true;
else {
int ceilIndex = findCeil(str,
str[i], i + 1, size - 1);
swapChar(&str[i], &str[ceilIndex]);
qsort(str + i + 1, size - i - 1,
sizeof(str[0]), compare);
}
}
}
int main() {
char str[] = "SNGY";
cout<<"All permutations of the string"<<str<<" are :\n";
printPermutations(str);
return 0;
}输出结果
All permutations of the stringSNGY are − GNSY GNYS GSNY GSYN GYNS GYSN NGSY NGYS NSGY NSYG NYGS NYSG SGNY SGYN SNGY SNYG SYGN SYNG YGNS YGSN YNGS YNSG YSGN YSNG
热门推荐
10 出院祝福语简短8字
11 新年探亲祝福语简短精辟
12 姨父生日祝福语简短精辟
13 生日祝福语贺卡老师简短
14 对别人新年祝福语简短
15 怎样给人送祝福语简短
16 朋友搬迁新房祝福语简短
17 祝福语同事离职英文简短
18 步入高中祝福语简短励志