public class Solution {
    public bool CanConstruct(string ransomNote, string magazine) {
        Dictionary<char, int> dic = new Dictionary<char, int>();

            //将ransomNote放入字典中,字典的值为本字符的存量
            foreach (var c in ransomNote)
            {
                if (!dic.ContainsKey(c))
                {
                    dic.Add(c, 1);
                }
                else
                {
                    dic[c]++;
                }
            }

            foreach (var m in magazine)
            {
                //如果包含此字符,并且存量大于0,则减少一个存量
                if (dic.ContainsKey(m) && dic[m] > 0)
                {
                    dic[m]--;
                }
            }

            bool result = true;

            foreach (var d in dic)
            {
                if (d.Value > 0)
                {
                    //还有某些字符没有用完
                    result = false;
                    break;
                }
            }

            return result;
    }
}

https://leetcode.com/problems/ransom-note/#/description

posted on 2017-04-19 11:11  Sempron2800+  阅读(173)  评论(0编辑  收藏  举报