zoukankan      html  css  js  c++  java
  • 383. 赎金信

    给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串:
    判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。
    如果可以构成,返回 true ;否则返回 false。
    题目说明:杂志的上各个字母均只能用一次。

    注:两个字符串均只含有小写字母。

    示例:
    canConstruct("aa", "ab") -> false
    canConstruct("aa", "aab") -> true



    思路:题目说明似乎是给题目注入了灵魂————一个字符只能用一次。
    magazine串的长度肯定要大些;
    将两个字符串都转为list,方便删减元素;
    用remove函数:默认删除原list中第一个匹配上的元素;
    遍历ransom串,一旦magazine串中没有匹配的字符就退出遍历;
    遍历指针未指向ransom串末尾,返回false;否则返回true。
     1 class Solution(object):
     2     def canConstruct(self, ransomNote, magazine):
     3         """
     4         :type ransomNote: str
     5         :type magazine: str
     6         :rtype: bool
     7         """
     8         # 首先转成集合,方便遍历和删“杂志”中的元素
     9         list1 = list(ransomNote)
    10         list2 = list(magazine)
    11         if len(list2) < len(list1):
    12             return False
    13         i = 0
    14         while i < len(list1):
    15             if list1[i] in list2:
    16                 list2.remove(list1[i])
    17                 i += 1
    18             else:
    19                 break
    20         if i != len(list1):
    21             return False
    22         else:
    23             return True
    24 
    25 
    26 if __name__ == '__main__':
    27     solution = Solution()
    28     print(solution.canConstruct("aa", "ab"))
    29     print(solution.canConstruct("aa", "aab"))
     
     
  • 相关阅读:
    0593. Valid Square (M)
    0832. Flipping an Image (E)
    1026. Maximum Difference Between Node and Ancestor (M)
    0563. Binary Tree Tilt (E)
    0445. Add Two Numbers II (M)
    1283. Find the Smallest Divisor Given a Threshold (M)
    C Primer Plus note9
    C Primer Plus note8
    C Primer Plus note7
    C Primer Plus note6
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12682134.html
Copyright © 2011-2022 走看看