LeetCode 383. Ransom Note
题目
Given two stings ransomNote and magazine , return true if ransomNote can be constructed from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote .
思路
和之前的题解法差不多。先对magazine 里的每个字母计数。再从结果中减去ransomNote 的计数。小于零则返回false 。
答案
public boolean isAnagram(String s, String t) {
int[] alphabet = new int[26];
for (int i = 0; i < s.length(); i++) {
alphabet[s.charAt(i) - 'a']++;}
for (int i = 0; i < t.length(); i++) {
alphabet[t.charAt(i) - 'a']--;}
for (int i : alphabet) {
if (i != 0){
return false;}}
return true;
}
**解法有参考
|