一个字符串是否为另一个字符串的排序

Tags
算法
C语言
ID
42
 
#include <stdio.h> #include <string.h> #include <stdlib.h> // 比较函数用于快速排序 int compare(const void *a, const void *b) { return *(const char *)a - *(const char *)b; } // 函数用于检查两个字符串是否具有相同的字符排列 int arePermutations(const char *str1, const char *str2) { // 如果字符串长度不同,则它们不可能是排列 if (strlen(str1) != strlen(str2)) return 1; // 复制字符串并排序 char sorted_str1[256]; char sorted_str2[256]; strcpy(sorted_str1, str1); strcpy(sorted_str2, str2); qsort(sorted_str1, strlen(sorted_str1), sizeof(char), compare); qsort(sorted_str2, strlen(sorted_str2), sizeof(char), compare); // 比较排序后的字符串 return strcmp(sorted_str1, sorted_str2); }
如果使用 qsort 函数的话,就很简单。另外,这里只支持 ascii 代码。