Files
leetcode-master/problems/0383.RansomNote.md
youngyangyang04 880ffa83b0 Update
2020-05-18 00:28:44 +08:00

68 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
https://leetcode-cn.com/problems/ransom-note/
## 思路
这道题题意很清晰就是用判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成但是这里需要注意两点1.
*  第一点“为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思”  这里*说明杂志里面的字母不可重复使用。*
* 第二点 “你可以假设两个字符串均只含有小写字母。” *说明只有小写字母*,这一点很重要
## 一般解法
那么第一个思路其实就是暴力枚举了两层for循环不断去寻找代码如下
```C++
// 时间复杂度: O(n^2)
// 空间复杂度O(1)
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for (int i = 0; i < magazine.length(); i++) {
for (int j = 0; j < ransomNote.length(); j++) {
if (magazine[i] == ransomNote[j]) {
ransomNote.erase(ransomNote.begin() + j);
break;
}
}
}
if (ransomNote.length() == 0) {
return true;
}
return false;
}
};
```
这里时间复杂度是比较高的而且里面还有一个字符串删除也就是erase的操作也是费时的当然这段代码也可以过这道题
我们想一想优化解法
## 优化解法
因为题目所只有小写字母,那我们可以采用空间换区时间的哈希策略, 用一个长度为26的数组还记录magazine里字母出现的次数然后再用ransomNote去验证这个数组是否包含了ransomNote所需要的所有字母。
代码如下:
```C++
// 时间复杂度: O(n)
// 空间复杂度O(1)
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int record[26] = {0};
for (int i = 0; i < magazine.length(); i++) {
record[magazine[i]-'a'] ++;
}
for (int j = 0; j < ransomNote.length(); j++) {
record[ransomNote[j]-'a']--;
if(record[ransomNote[j]-'a'] < 0) {
return false;
}
}
return true;
}
};
```