题目是这样的
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
题目分析:第二个字符串中,是否包含第一个字符串中出现的所有字符(重复的算出现的次数),第二个字符串中的每一个字符可以使用一次。
这个想起来挺简单:判断第一个字符串中每一个字符出现的次数与第二个字符串中每一个字符串出现的次数进行比较。
借鉴他人思路(只考虑小写的英文字母):
public static boolean canConstruct(String ransomNote, String magazine) { if (ransomNote.length() > magazine.length()) { return false; } int[] a = new int[26];// 最多有26个字母 int[] b = new int[26]; for (int i = 0; i < ransomNote.length(); i++) { a[ransomNote.charAt(i) - 'a']++;// 进行字符个数的判断,如果已经存在了,就++(这里最重要) } for (int i = 0; i < magazine.length(); i++) { b[magazine.charAt(i) - 'a']++; } for (int i = 0; i < a.length; i++) { if (a[i] > b[i]) {// 判断第一个数组中的每一个是否有大于第二个数组的值 return false; } } return true; }
代码很简单,关键是思路!思路!思路!
重要的事说三遍哈哈^_^