IncredibleThings

导航

LeetCode-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


开26个数组存入magzine字母的数目,每个位置存对应字母的数目;

对ransom字符串来说,每读一个字母,则将对应位置的字母数目减一,如果某个字母数目小于0了,则表明字母不够用,从而返回false;否则返回true。

 

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] charCount = new int[26];
        for(int i=0; i<magazine.length(); i++){
            charCount[magazine.charAt(i) - 'a']++;
        }
        for (int i=0; i< ransomNote.length(); i++){
            charCount[ransomNote.charAt(i)- 'a']--;
            if(charCount[ransomNote.charAt(i)- 'a']<0){
                return false;
            }
        }
        return true;
        
    }
}

 另一种用hashmap的解法:

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> map = new HashMap();
        for (int i=0; i< magazine.length(); i++){
            char c = magazine.charAt(i);
            if(map.containsKey(c)){
                int value = map.get(c);
                map.put(c, value+1);
            }
            else{
                map.put(c,1);
            }
        }
        for(int i=0; i<ransomNote.length(); i++){
            char c = ransomNote.charAt(i);
            if(!map.containsKey(c)){
                return false;
            }
            else {
                if(map.get(c)== 0){
                    return false;
                }
                else{
                    map.put(c,map.get(c)-1);
                }
                
            }
        }
        return true;
    }
}

 

posted on 2017-12-12 12:04  IncredibleThings  阅读(105)  评论(0编辑  收藏  举报