[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中,值是字符出现的数量,然后循环遍历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)
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容