字符串s2是否能由s1中的字符构成

来源:互联网 发布:怎样加入淘宝客赚佣金 编辑:程序博客网 时间:2024/04/29 18:04

如果s2能由s1构成的话,s1中的每个字符出现的次数都应不少于s2中每个字符出现的次数。

♦ 下面程序使用hashmap纪录s1中每个字符出现的次数。然后遍历s2, 其中每个字符出现一次,就让hashmap中对应的值(次数)减1. 一旦这个值为0,就可得返回false。

♦ 如果遍历完s2,还没有返回false,就说明s1的字符是足够的。

#include <iostream>#include <string>#include <map>using namespace std;bool canCompose(string newspaper, string message) {    map<char, int> hashMap;    int i;    if (newspaper.length() < message.length()) {        return false;    }    for (i = 0; i < newspaper.length(); i++) {        hashMap[newspaper[i]]++;    }    for (i = 0; i < message.length(); i++) {        if (hashMap[message[i]] == 0) {            return false;        }        hashMap[message[i]]--;    }    return true;}int main(void){    string s1 = "helloworld, and how you are you?!";    string s2 = "ahe ?!";    if (canCompose(s1, s2)) {        cout << "s1 can compose s2" << endl;    } else {        cout << "s1 can not compose s2" << endl;    }    return 0;}
0 0
原创粉丝点击