当前位置: 代码迷 >> 综合 >> 给定两个字符串newspaper和message,判定message是否能用newspaper中的字符组成
  详细解决方案

给定两个字符串newspaper和message,判定message是否能用newspaper中的字符组成

热度:7   发布时间:2024-01-20 03:12:05.0

给定两个字符串newspaper和message,判定message是否能用newspaper中的字符组成。

分析:message中用到的字符必须出现在newspaper中。其次,message中任意字符出现的次数一定少于其在newspaper中出现的次数。统计一个元素集中元素出现的次数,我们就应该想到hash table。

bool canCompose(string newspaper,string message)
{unordered_map<char,int> hashMap;int i=0;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;
}

 

  相关解决方案