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。
53 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
1313 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.
899 0
|
16天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
16天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
17天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
|
17天前
|
算法
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)