CTCI系列--1.3 判断两个字符串是否互为变换(C语言)

本文提供两种方法判断两个字符串是否互为变换。一种是对字符串排序后进行比较;另一种是统计字符串中各字符出现次数并对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:Given two strings,write a method to decide if one is a permutation of the other.

对于给定的两个字符串,写一个方法判断其中一个是否是另一个的变换。

解题思路

分析题目,要判断一个字符串是否是另一个字符串变换得来。那么首先,这两个字符串必须==长度相等==;其次两个字符串中的每个字符必须相一致。

那么,我们代码可以这样实现:
- 先判断两个字符串的长度,若不相等则返回false;若相等进入下一步
- 对两个字符串分别进行排序
- 排序完,使用memcpy()函数进行内存对比,如相等则返回true,不相等则返回false

代码如下:

#include <stdio.h>
#include <string.h>

void swap(char *a, char*b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

void sort_string(char *str,int len)
{
    int i, j;
    char flag = 0;
    for (i = 0; i < len; i++)
    {
        flag = 0;
        for (j = 1; j < len - i - 1; j++)
        {
            if (str[j] > str[j + 1])
            {
                swap(&str[j], &str[j + 1]);
                flag = 1;
            }
        }

        if (0 == flag)
            break;
    }
}

//返回1 ---- 字符串互为变换 0 ---- 字符串不是
int campara_str(char *str1, char *str2)
{
    int len1=0, len2 = 0;

    len1 = strlen(str1);
    len2 = strlen(str2);

    sort_string(str1, len1);
    sort_string(str2, len2);

    if (memcmp(str1, str2, len1) == 0)
        return 1;
    else
        return 0;
}

int main(void)
{
    char buf1[6];
    char buf2[6];

    memset(buf1, 0, sizeof(buf1));
    memset(buf2, 0, sizeof(buf2));
    strcpy(buf1, "hello");
    strcpy(buf2, "helol");

    if (campara_str(buf1, buf2))
    {
        printf("The two strings is anagram!\n");
    }
    else
    {
        printf("The two strings is not anagram!\n");
    }

    memset(buf2, 0, sizeof(buf2));
    strcpy(buf2, "helio");

    if (campara_str(buf1, buf2))
    {
        printf("The two strings is anagram!\n");
    }
    else
    {
        printf("The two strings is not anagram!\n");
    }

    getchar();

    return 0;
}

PS: 不要直接比较两个静态字符串campara_str("hello", "helol") ,const数据是无法修改的,排序时会出错。

运行结果

运行结果

另一种方法

还有一种方法,就是统计两个字符串中每个字符的出现次数,然后做比较。若出现次数一致则返回true;否则返回flase.
算法如下:

int campara_str2(char *str1, char *str2)
{
    int letter1[256],letter2[256];

    memset(letter1, 0, sizeof(letter1));
    memset(letter2, 0, sizeof(letter2));

    while (*str1 != '\0')
    {
        letter1[*str1++]++;
    }

    while (*str2 != '\0')
    {
        letter2[*str2++]++;
    }

    if (memcmp((void *)&letter1, (void *)&letter2, sizeof(letter1)) == 0)
        return 1;
    else
        return 0;
}

文章转载自我的个人博客
本文固定链接为:http://linuxue.com/archives/18

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值