您的位置:首页 > 其它

LeetCode_383. Ransom Note

2017-02-03 19:10 381 查看
383. Ransom Note:

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:

You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true


题意理解:

赎金条问题,能否从杂志中找到赎金条中的字符。即给定两个字符串,判断其中一个字符串能否由另外一个字符串中的字符组成,字符不能重复使用。

解题思路:

先判断两字符串长度,若赎金条字符长度大于杂志字符长度,则判定false;再对排序后的两字符串进行字符串的逐个比较。占用额外空间较少。运行耗时(53ms)。

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
if (ransomNote.size()>magazine.size())
return false;
int i=0, j=0;
sort(ransomNote.begin(), ransomNote.end());
sort(magazine.begin(), magazine.end());
while(i<ransomNote.size() && j<magazine.size())
{
if (magazine[j]==ransomNote[i])
{
++i;
}
++j;
}
if (i==ransomNote.size())
return true;
else
return false;

}
};


Top Solution:

利用unordered_map/vector先统计magazine中的字符,再比较ransomNote中相应字符的数量是否满足要求。

(运行时间49ms/53ms)

unordered_map 是C++11新特性,与map类似。都是存储key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序。

内部实现机理:

1.map:map内部实现了一个红黑树,该结构具有自动排序的功能,因此map内部的所有元素都是有序的,红黑树的每一个节点都代表着map的一个元素,因此,对于map进行的查找,删除,添加等一系列操作都相当于是对红黑树进行相应的操作,故红黑树的效率决定了map的效率。

2. unordered_map: unordered_map内部实现了一个哈希表,因此其元素的排列顺序是杂乱的,无序的。

以上定义reference:

http://blog.csdn.net/u012530451/article/details/53228098

version_2:

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> map;
for (int i=0; i<magazine.size(); i++)
++map[magazine[i]];
for (int j=0; j<ransomNote.size(); j++)
{
if (--map[ransomNote[j]]<0)
return false;
}
return true;
}
};


version_3:

class Solution {
public:
bool canConstruct(string randomNote, string magazine) {
vector<int> num(26, 0);
for (int i=0; i<magazine.size(); i++)
++num[magazine[i]-'a'];
for (int j=0; j<ransomNote.size(); j++)
{
if (--num[ransomNote[j]]<0)
return false;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode