赎金信
赎金信
此题采用数组解法,只需分别遍历两个数组,记录各元素出现次数即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public boolean canConstruct(String ransomNote, String magazine) { int[] res = new int[26]; if(ransomNote.length() > magazine.length() ) return false;
char[] maga = magazine.toCharArray(); for(int i = 0;i<magazine.length();i++){ res[maga[i] - 'a']++; } char[] ran = ransomNote.toCharArray(); for(int i = 0; i<ransomNote.length();i++ ){ res[ran[i] - 'a']--; if(res[ran[i] - 'a'] < 0 ) return false; }
return true; }
}
|