在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 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特