383. Ransom Note【easy】

时间:2023-03-10 02:30:09
383. Ransom Note【easy】

383. Ransom Note【easy】

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

解法一:

 class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
map<char, int> m_rans; for (int i = ; i < ransomNote.length(); ++i) {
++m_rans[ransomNote[i]];
} for (int i = ; i < magazine.length(); ++i) {
if (m_rans.find(magazine[i]) != m_rans.end()) {
--m_rans[magazine[i]];
}
} for (map<char, int>::iterator it = m_rans.begin(); it != m_rans.end(); ++it) {
if (it->second > ) {
return false;
}
} return true;
}
};

解法二:

 public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] arr = new int[];
for (int i = ; i < magazine.length(); i++) {
arr[magazine.charAt(i) - 'a']++;
}
for (int i = ; i < ransomNote.length(); i++) {
if(--arr[ransomNote.charAt(i)-'a'] < ) {
return false;
}
}
return true;
}
}

参考@yidongwang 的代码。

解法三:

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

参考@haruhiku 的代码

解法四:

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

参考@haruhiku 的代码