LeetCode之Ransom Note

简介: LeetCode之Ransom Note

1、题目

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

 

2、代码实现

public class Solution {
      public  boolean canConstruct(String ransomNote, String magazine) {
       if (magazine == null)
         return false;
       if (ransomNote == null)
         return false;
       if (ransomNote.length() == 0 && magazine.length() == 0) 
         return true;
       List<Character> list = new ArrayList<Character>();
       for (char c : magazine.toCharArray()) {
         list.add(Character.valueOf(c));
       }
       if (ransomNote.length() == magazine.length()) {
         for (int i = 0; i < ransomNote.length(); i++) {
           if (!list.remove(Character.valueOf(ransomNote.charAt(i)))) {
             return false;
           }
         }
         return true;
       } else {
         for (int i = 0; i < ransomNote.length(); i++) {
           if (!list.remove(Character.valueOf(ransomNote.charAt(i)))) {
             return false;
           }
         }
         if (list.size() > 0) {
           return true;
         }
       }
         return false;
  }
}


相关文章
LeetCode 383. Ransom Note
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
141 0
LeetCode 383. Ransom Note
[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
1431 0
|
Java
[LeetCode] Ransom Note
A very typical application of hash maps. Since I am now learning Java, I code in Java. The following code uses toCharArray() and getOrDefault(), which are learnt from this post.
989 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
343 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
198 6
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
439 2
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
344 3
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口

热门文章

最新文章