[LeetCode By Go 34]383. 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.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

解題思路

把magazine上的字符串放進map中,值是字符出現(xiàn)的數(shù)量,然后循環(huán)遍歷ransom上的字符,如果map中有則值減一,如果沒有或者值為0則返回false

代碼

ransomNote.go

package _383_Ransom_Note


func CanConstruct(ransomNote string, magazine string) bool {
    var magazineMap map[rune]int
    magazineMap = make(map[rune]int)
    magazineRune := []rune(magazine)

    for _, v := range magazineRune {
        magazineMap[v]++
    }

    ransomNoteRune := []rune(ransomNote)
    for _, letter := range ransomNoteRune {
        tmp, ok := magazineMap[letter]
        if !ok || tmp <= 0 {
            return false
        } else {
            magazineMap[letter]--
        }
    }

    return true
}

測試

ransomNote_test.go

package _383_Ransom_Note

import "testing"

func TestCanConstruct(t *testing.T) {
    var tests = []struct{
        a string
        b string
        output bool
    } {
        {"aa", "ab", false},
    }

    for _, test := range tests {
        ret := CanConstruct(test.a, test.b)

        if ret == test.output {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %+v", test.output, ret)
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容