zoukankan      html  css  js  c++  java
  • [LeetCode] 383. Ransom Note

    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") -> false
    canConstruct("aa", "ab") -> false
    canConstruct("aa", "aab") -> true
    

    两个字符串输入参数,判断第二个string是否能拼出第一个字符串
    第二个字符串象是一本杂志,从杂志里剪出很多个字符拼成第一个字符串,所以要有对应的字符而且数量要足够

    能很简单地写出一个非最优解版本

    bool canConstruct(string ransomNote, string magazine)
    {
        int dic1[26] = {0};
        int dic2[26] = {0};
        for(char c : ransomNote)
        {
            dic1[c-'a']++;
        }
    
        for(char c : magazine)
        {
            dic2[c-'a']++;
        }
    
        bool result = true;
        for(int i = 0; i < 26, dic1[i] !=0; i++)
        {
            if (dic1[i] > dic2[i])
            {
                result = false;
            }
        }
    
        return result;
    }
    

    再把一些步骤合并起来,可以只统计magazine的字符数量,直接在ransomNote的循环中判断字符数量是否足够

    bool canConstruct(string ransomNote, string magazine) 
    {
        int dic1[26] = {0};
    
        for (char c : magazine)
        {
            dic1[c - 'a']++;
        }
    
        for(char c : ransomNote)
        {
            if (dic1[c - 'a'] == 0)
            {
                return false;
            }
    
            dic1[c - 'a']--;
        }
    
        return true;
    }
    

    LeetCode其他代码也是这个思路,略

  • 相关阅读:
    第02组 Alpha冲刺 (6/6)
    面向对象分析设计考试复习【历年卷】
    第02组 Alpha冲刺 (5/6)
    第02组 Alpha冲刺 (4/6)
    第02组 Alpha冲刺 (3/6)
    第02组 Alpha冲刺 (2/6)
    第02组 Alpha冲刺 (1/6)
    linux内核结构
    从别人的博客学习
    递归的认识
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9473502.html
Copyright © 2011-2022 走看看