(LeetCode)Ransom Note --- 勒索信(字符串问题)

来源:互联网 发布:win7虚拟机mac os x 编辑:程序博客网 时间:2024/05/17 20:29


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") -> falsecanConstruct("aa", "ab") -> falsecanConstruct("aa", "aab") -> true


解题分析:

  字符串匹配问题,注意几点,首先

只要统计两个字符串中对应字符的个数,以及存在的字符就OK了。



# -*- coding:utf-8 -*-__author__ = 'jiuzhang'from collections import Counterclass Solution(object):    def canConstruct(self, ransomNote, magazine):        if ransomNote == '':            return True        if magazine == '':            return False        note = Counter(ransomNote)        mag = Counter(magazine)        for i in note.keys():            print i            if None == mag.get(i) or not[i] > mag.get(i):                return False            else:                return True


0 0
原创粉丝点击