C 程序来查找给定字符串的排列
假设我们在一个数组中有几个字符串。我们必须在不同的行中找到它们的所有排列。
因此,如果输入类似于 strings = ["abc", "def", "ghi"],那么输出将是
abc def ghiabc ghi def
def abc ghi
def ghi abc
ghi abc def
ghi def abc
示例
让我们看看以下实现以获得更好的理解 -
#include <stdio.h>#include <string.h>
int next_permutation(int n, char **s){
for (int i = n - 1; i > 0; i--)
if (strcmp(s[i], s[i - 1]) > 0){
int j = i + 1;
for (; j < n; j++)
if (strcmp(s[j], s[i - 1]) <= 0)
break;
char *t = s[i - 1];
s[i - 1] = s[j - 1];
s[j - 1] = t;
for (; i < n - 1; i++, n--){
t = s[i];
s[i] = s[n - 1];
s[n - 1] = t;
}
return 1;
}
for (int i = 0; i < n - 1; i++, n--){
char *t = s[i];
s[i] = s[n - 1];
s[n - 1] = t;
}
return 0;
}
int main(){
char *strings[] = {"abc", "def", "ghi"};
int n = 3;
do{
for (int i = 0; i < n; i++)
printf("%s%c", strings[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, strings));
}
输入
{"abc", "def", "ghi"}输出结果
abc def ghiabc ghi def
def abc ghi
def ghi abc
ghi abc def
ghi def abc
以上是 C 程序来查找给定字符串的排列 的全部内容, 来源链接: utcz.com/z/360535.html