December 1, 2023

Viiisit [LeetCode] - 383. Ransom Note

#php#javascript#ruby

keep learning, keep coding!

Problem - Ransom Note

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

翻譯蒟蒻

給定兩個字串 ransomNote 與 magazine,觀察 ransomNote 的字是否有在 magazine 出現,也就是說 magazine 中的字母是否可以構成 ransomNote,而且每個字母在 magazine 中只能使用一次。有則 true,否則 false。


Solution - JavaScript

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function(ransomNote, magazine) {
for (const char of magazine) {
ransomNote = ransomNote.replace(char, '')
}
return !ransomNote
};

for…of Usage

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function(ransomNote, magazine) {
// 用一個空的 object 來記錄字母
let record = {}
for (const char of magazine) {
record[char] = record[char] ? record[char] + 1 : 1
}
for (const char of ransomNote) {
// 如果 record 中某字母的次數為 0 或 undefined,則返回 false。
if (!record[char]) {
return false
}
record[char]--
}
return true
};

Solution - Ruby

Solution 1:

1
2
3
4
5
6
def can_construct(ransom_note, magazine)
magazine.each_char do |char|
ransom_note.sub!(char, '')
end
ransom_note.empty?
end

Solution 2:

1
2
3
def can_construct(ransom_note, magazine)
ransom_note.chars.uniq.all? { |char| ransom_note.count(char) <= magazine.count(char) }
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
function canConstruct($ransomNote, $magazine) {
$record = [];
for ($i = 0; $i < strlen($magazine); $i++) {
$record[$magazine[$i]] = isset($record[$magazine[$i]]) ? $record[$magazine[$i]] + 1 : 1;
}
for ($i = 0; $i < strlen($ransomNote); $i++) {
if (!isset($record[$ransomNote[$i]]) || $record[$ransomNote[$i]] == 0) {
return false;
}
$record[$ransomNote[$i]]--;
}
return true;
}

PHP 方法筆記

LeetCode 傳送門 - Ransom Note