• 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"))
     
     
  • 相关阅读:
    Steps to Writing Well----Reading Notes
    How to Improve Reading Skills
    Requirement-Driven Linux Shell Programming
    Linux tar command usage
    MVC和MVVM模型
    js中特殊的宏任务
    js 超浓缩 双向绑定
    JavaScript 中的遍历详解
    多段动画整合为一个动画的思路
    Js事件循环(Event Loop)机制
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12682134.html
Copyright © 2020-2023  润新知