mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-28 03:33:13 +08:00
Update
This commit is contained in:
67
problems/0383.RansomNote.md
Normal file
67
problems/0383.RansomNote.md
Normal file
@ -0,0 +1,67 @@
|
||||
## 题目地址
|
||||
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;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
Reference in New Issue
Block a user