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 };
  • 相关阅读:
    【微信小程序】数组操作
    iOS中html打开APP传参
    给radio加自己的样式(图片)
    TCP和IP的三次握手和第四次挥手
    什么是HTTP协议
    http和https的区别
    微信小程序-点击图片预览
    JAVASE
    thinkphp自学笔记
    前端必须掌握的30个CSS选择器
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7498915.html
Copyright © 2011-2022 走看看