LeetCode 383. Ransom Note

原题链接在这里:https://leetcode.com/problems/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的char们能否组成第一个string. 用freq来maintain magazine的么个char的个数,再把ransomNote的对应char个数减掉,若出现负数就不能通过magazine create ransomNote.

Time Complexity: O(magazine.length() + ransomNote.length()). Space: O(1)

AC Java:

 1 public class Solution {
 2     public boolean canConstruct(String ransomNote, String magazine) {
 3         if(ransomNote == null || magazine == null){
 4             throw new IllegalArgumentException("Invalid input string.");
 5         }
 6         
 7         int [] freq = new int[256];
 8         for(int i = 0; i<magazine.length(); i++){
 9             freq[magazine.charAt(i)]++;
10         }
11         
12         for(int i = 0; i<ransomNote.length(); i++){
13             if(--freq[ransomNote.charAt(i)] < 0){
14                 return false;
15             }
16         }
17         
18         return true;
19     }
20 }

AC C++:

 1 class Solution {
 2 public:
 3     bool canConstruct(string ransomNote, string magazine) {
 4         int map[26] = {0};
 5         for(char c : magazine){
 6             map[c - 'a']++;
 7         }
 8 
 9         for(char c : ransomNote){
10             if(map[c - 'a']-- == 0){
11                 return false;
12             }
13         }
14 
15         return true;
16     }
17 };

跟上Stickers to Spell Word.

posted @ 2017-01-08 08:44  Dylan_Java_NYC  阅读(207)  评论(0编辑  收藏  举报