lixiaoyao123

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"\n"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"\n"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粗暴式解法。

发表于 2019-03-19 10:49  李逍遥123  阅读(111)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章:

  • 2023-03-31
  • 2022-02-12
  • 2021-12-09
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2021-09-20
猜你喜欢
  • 2022-01-15
  • 2022-01-16
  • 2021-11-12
  • 2023-04-06
  • 2023-04-04
  • 2023-04-05
  • 2022-01-03
相关资源
相似解决方案