leetcode—383. Ransom Note string类型转化为list类型,list中删除某个字符

来源:互联网 发布:产品运营数据分析 编辑:程序博客网 时间:2024/06/10 15:15

题目:

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

题意:

给定两个字符串,判断其中一个字符串能否由另一个字符串生成,其中,每个字符串只能使用一次。


代码:

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        
        flag = True
        
        magazine = list(magazine)     #这样可以用remove方法来删除magazine中已经在ransomNote中的字符
        
        for x in ransomNote :
            if x in magazine :
                magazine.remove(x)
            else :
                flag = False
                break
        return flag


笔记:

1、python 布尔类型的取值 ,记住书写形式,第一个字母大写:True, False

2、字符串定义后,元素值不能删除修改(实际测试本代码中用magazine.replace(x,'') 来实现将已出现的字符删除,不生效),但是list可以。故将string类型转化为list类型,可以实现对string元素的删除修改。 

0 0
原创粉丝点击