Ransom Note

Given a ransom Note string and a magzine string, determine if this ransom string can be constructed from the letters in the magzine string. Each letter in the magzine string can only be used once. There are only lowercase letters in both strings.

Solution:

1. build a hashtable using an array of size 26. The index for each letter will be letter-'a'.

2. scan the magzine string and store the number of each letter in the hashtable.

3. scan the ransom string and each time if the number of the letter scanned is equal to 0, return false. we let the number of the letter scanned in the hashtable minus 1.

Code:

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

 

posted @ 2017-06-18 09:29  小风约定  阅读(74)  评论(0)    收藏  举报