[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)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/403cdd4b2dbb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞