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

  给定两个字符串,ransomNote和magazine,判断ransomNote是否能够由magazine中的字符构成,要求magazine中的字母只能使用一次。说白了就是子序列问题。

    public static  boolean canConstruct(String ransomNote, String magazine) {
        int array[] = new int[26];
        for(int i = 0; i < magazine.length(); i++)
            array[magazine.charAt(i) - 'a']++;
        for(int i = 0; i < ransomNote.length(); i++)
        {
            if(array[ransomNote.charAt(i) - 'a'] - 1 < 0) //可以直接合并为--array[ransomNote.charAt(i) - 'a']
            {
                return false;
            }
            array[ransomNote.charAt(i) - 'a']--; 
        }
        return true;
    }
原文地址:https://www.cnblogs.com/wxshi/p/7609573.html