给定两个字符串newspaper和message,检查是否能够使用newspaper中的字母来组成message

来源:互联网 发布:unity3d加速器 编辑:程序博客网 时间:2024/05/01 21:37

分析什么情况下newspaper中的字符能组成message?
1。message中用到的字符必须都出现在newspaper中。
2。message中各个字符出现的次数一定少于其在newspaper中的出现次数。
一旦需要统计元素集中元素出现的次数,就应该想到哈希表。键key是字符,值value是该字符在newspaper中出现的次数。
So,若message用到的字符没有出现在哈希表中,则构成失败;若message中用到的字符数多余其在newspaper中出现的次数,则构成失败。
复杂度分析:加上message长度为m,newspaper中长度为n,算法需要hash整个message和newspaper,故时间复杂度为O(m+n)。假设字符集大小为c,则平均空间O(c)。
代码参考:

bool canCompose(string newspaper, string message){    unordered_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.count(message[i])==0){            return false;        }        if(--hashMap[message[i]]<0){            return false;        }    }    return true;}

注意,count(key)是unordered_map的一个函数, 返回unordered_map中指定键key对应的元素,若存在则返回1,否则返回0。

0 0
原创粉丝点击