383. Ransom Note

383. Ransom Note

Question

Given two strings ransomNote and magazine, return true* if ransomNote can be constructed by using the letters from magazine and false otherwise*.

Each letter in magazine can only be used once in ransomNote.

Solution

数组统计,统计magazine内的字符。
遍历ransomNote,如果对字符数组位置为0则返回false。
每次遍历减少数组统计结果。

最后返回true。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
char[] bin = new char[26];

for(char c : magazine.toCharArray()) bin[c-'a']++;
for(char c : ransomNote.toCharArray()){
if(bin[c-'a'] == 0) return false;
bin[c-'a']--;
}

return true;
}
}
Author

Xander

Posted on

2022-08-25

Updated on

2022-08-25

Licensed under

Comments