数据结构和算法经典100题-第25题

判断两个字符串是否互为变形词

题目要求:
给定两个字符串str1和str2,若str1和str2中的字符种类一样,每个字符出现的频率一样,那么str1和str2就互为变形词。


题目分析:
可以先把一个字符串中字符出现的频率统计出来,然后再验证另一个字符串字符出现的频率。
Okay,no code say what?

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

using namespace std;

bool isDeformation(string &str1,string &str2) {
    if (str1.empty() || str2.empty() || str1.size() != str2.size()) {
        return false;
    }

    map<char,int> mapCount;
    for (string::iterator i = str1.begin(); i != str1.end(); ++i) {
        mapCount[*i]++;
    }

    for (string::iterator i = str2.begin(); i != str2.end(); ++i) {
        mapCount[*i]--;
        if (mapCount[*i] < 0)
            return false;
    }
    return true;
}


int main(void) {
    string str1("hello");
    string str2("eollh");
    string str3("hellq");
    if (isDeformation(str1,str2)) {
        cout<<" str1 & str2 is deformation."<<endl;
    } else {
        cout<<" str1 & str2 is not deformation."<<endl;
    }

    if (isDeformation(str1,str3)) {
        cout<<" str1 & str3 is deformation."<<endl;
    } else {
        cout<<" str1 & str3 is not deformation."<<endl;
    }
    return 0;

}

路漫漫其修远兮,最近工作很忙啊,这个系列得加快更新了…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值