zoukankan      html  css  js  c++  java
  • LeetCode: 383 Ransom Note(easy)

    题目:

    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.

    1 canConstruct("a", "b") -> false
    2 canConstruct("aa", "ab") -> false
    3 canConstruct("aa", "aab") -> true

    代码:

     1 class Solution {
     2 public:
     3     bool canConstruct(string ransomNote, string magazine) {
     4         if (ransomNote == "")
     5             return true;
     6         for (auto c : ransomNote){
     7             int position = magazine.find_first_of(c); 
     8             if (position != magazine.npos)
     9                 magazine.erase(position, 1);
    10             else
    11                 return false;        
    12         }
    13        return true;    
    14     }
    15 };

    别人的:

     1 class Solution {
     2 public:
     3     bool canConstruct(string ransomNote, string magazine) {
     4         int mp[26] = {0};
     5         for(auto c : magazine) {
     6             mp[c - 'a']++;
     7         }
     8         for(auto r : ransomNote) {
     9             mp[r - 'a']--;
    10             if(mp[r - 'a'] < 0) return false;
    11         }
    12         return true;
    13     }
    14 };
  • 相关阅读:
    指定的架构无效。错误: CLR 类型到 EDM 类型的映射不明确
    win7IIS错误修改路径最全的
    如何设置textarea光标默认为第一行第一个字符
    我的Hexo网站
    Leetcode Round 4 记录
    几何编程题
    Leetcode Round 3 记录
    几何概型
    Roman Number & Integer
    Single Number
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7498915.html
Copyright © 2011-2022 走看看