未分類

Ransom Note

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.

1
2
3
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
提示 解題應用
String HashTable

Default:

1
2
3
func canConstruct(ransomNote string, magazine string) bool {
}

解答思路:

要判斷一字串中是否包含另一字串的每一個字母,順序甚至是被打散都沒關係,只要有出現就可以了,那麼我們只要用hashmap將需要被包含的每個字母放入,而在遍歷目標字串時檢查hashmap是否有該字母,有的話就將其從hashmap中取出,最後遍歷完成時,如果hashmap為空表示目標字串完全包含了另一字串的每一個字母。

程式碼解說:

一開始初始化完一hashmap之後,就將要被包含的字串ransomNote的每個字母放入hashmap,其中key為rune值而value則是用來存放每個字母出現的次數,再來就是開始核對目標字串magazine的字母是否有在hashmap之中,如果有就將數量-1,該字母的數量已經歸0了的話則直接將其從hashmap中移除,最後在目標字串遍歷結束之後檢查hashmap的長度,完全包含的情況下長度會為0回傳true,否則回傳false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
hashMap := make(map[rune]int)
for _, v := range ransomNote {
hashMap[v] += 1
}
for _, v := range magazine {
amount, ok := hashMap[v]
if ok {
if amount-1 == 0 {
delete(hashMap, v)
} else {
hashMap[v] = amount - 1
}
}
}
if len(hashMap) == 0 {
return true
}
return false

完整程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func canConstruct(ransomNote string, magazine string) bool {
hashMap := make(map[rune]int)
for _, v := range ransomNote {
hashMap[v] += 1
}
for _, v := range magazine {
amount, ok := hashMap[v]
if ok {
if amount-1 == 0 {
delete(hashMap, v)
} else {
hashMap[v] = amount - 1
}
}
}
if len(hashMap) == 0 {
return true
}
return false
}

總結:

要判斷一字串中是否包含另一字串的每一個字母,順序、位置不限,只要用hashmap將需要被包含的每個字母放入,而在遍歷目標字串時檢查hashmap是否有該字母,有的話就將其從hashmap中取出,最後遍歷完成時,如果hashmap為空表示目標字串完全包含了另一字串的每一個字母。

分享到