c语言判断异位数
时间: 2023-08-03 09:03:31 浏览: 40
异位数指的是具有相同字符但排列顺序不同的两个字符串。以下是用C语言实现判断两个字符串是否为异位数的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int isAnagram(char *s, char *t) {
int len1 = strlen(s);
int len2 = strlen(t);
if (len1 != len2) return 0; // 长度不相等,直接返回不是异位数
int count[26] = {0}; // 记录每个字符出现的次数
for (int i = 0; i < len1; i++) {
count[s[i]-'a']++; // 统计字符串s中每个字符出现的次数
count[t[i]-'a']--; // 统计字符串t中每个字符出现的次数
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0) return 0; // 如果有任何一个字符的出现次数不相等,则不是异位数
}
return 1;
}
int main() {
char s[MAX_LEN], t[MAX_LEN];
printf("请输入两个字符串,用空格隔开:\n");
scanf("%s%s", s, t);
if (isAnagram(s, t)) {
printf("%s和%s是异位数\n", s, t);
} else {
printf("%s和%s不是异位数\n", s, t);
}
return 0;
}
```
以上代码中,首先判断两个字符串的长度是否相等,如果不相等则直接返回不是异位数。然后用一个长度为26的数组count统计每个字符在字符串s和t中出现的次数,最后遍历数组count,如果有任何一个字符的出现次数不相等,则不是异位数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)