zoukankan      html  css  js  c++  java
  • Leecode刷题之旅-C语言/python-383赎金信

    /*
     * @lc app=leetcode.cn id=383 lang=c
     *
     * [383] 赎金信
     *
     * https://leetcode-cn.com/problems/ransom-note/description/
     *
     * algorithms
     * Easy (44.98%)
     * Total Accepted:    5K
     * Total Submissions: 11.1K
     * Testcase Example:  '"a"
    "b"'
     *
     * 给定一个赎金信 (ransom)
     * 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回
     * true ;否则返回 false。
     * 
     * (题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)
     * 
     * 注意:
     * 
     * 你可以假设两个字符串均只含有小写字母。
     * 
     * 
     * canConstruct("a", "b") -> false
     * canConstruct("aa", "ab") -> false
     * canConstruct("aa", "aab") -> true
     * 
     * 
     */
    bool canConstruct(char* ransomNote, char* magazine) {
        if (ransomNote == NULL || magazine == NULL) {
            return false;
        }
        int index[26];
        for(int i=0;i<26;i++){
            index[i]=0;
        }
        for (int i = 0; i <strlen(magazine); i++) {
            index[magazine[i]-'a']++;
        }
        for (int j = 0; j <strlen(ransomNote); j++) {
            if (--index[ransomNote[j]- 'a'] < 0) {
                return false;
            }
        }
        return true;
    }

    这里的思路就是,建立一个数组,26个位置,0代表a,以此类推。

    然后统计杂志中也就是magazine中所有各个字符出现的次数。

    然后在杂志中出现一个字符就减掉index中的字符次数,其实相当于 买东西 和 库存 的含义。如果小于零的话就证明那个字符不够用,返回false;

    这里index不初始化的话就不行。。。(不知道为什么)

    -----------------------------------------------------------------------

    python:

    #
    # @lc app=leetcode.cn id=383 lang=python3
    #
    # [383] 赎金信
    #
    # https://leetcode-cn.com/problems/ransom-note/description/
    #
    # algorithms
    # Easy (44.98%)
    # Total Accepted:    5K
    # Total Submissions: 11.1K
    # Testcase Example:  '"a"
    "b"'
    #
    # 给定一个赎金信 (ransom)
    # 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true
    # ;否则返回 false。
    # 
    # (题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)
    # 
    # 注意:
    # 
    # 你可以假设两个字符串均只含有小写字母。
    # 
    # 
    # canConstruct("a", "b") -> false
    # canConstruct("aa", "ab") -> false
    # canConstruct("aa", "aab") -> true
    # 
    # 
    #
    class Solution:
        def canConstruct(self, ransomNote: str, magazine: str) -> bool:
            return all(ransomNote.count(c)<=magazine.count(c) for c in string.ascii_lowercase)

    python粗暴式解法。

  • 相关阅读:
    通过TortoiseGit上传项目到GitHub
    删除右键菜单中的Git Gui Here、Git Bash Here的方法
    block functions区块函数插件的定义与使用
    modifiers标量调节器插件的定义和使用
    functions函数插件的定义和使用
    smarty内置函数、自定义函数
    smarty类与对象的赋值与使用
    Smarty模板的引用
    Smarty的循环
    Smarty的条件判断语句
  • 原文地址:https://www.cnblogs.com/lixiaoyao123/p/10557141.html
Copyright © 2011-2022 走看看