您的位置:首页 > 其它

Leetcode 383. Ransom Note

2016-08-22 06:12 288 查看


383. Ransom Note

Total Accepted: 8831 Total Submissions: 20079 Difficulty: Easy


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


思路:

只要ransom中的所有letter都在magazine中出现并且数目小于等于该letter在magazine中出现的次数就可以了。

public class Solution { // 15ms
public boolean canConstruct(String ransomNote, String magazine) {
char[] one = ransomNote.toCharArray();
char[] two = magazine.toCharArray();

int[] table = new int[26];
for(int i = 0; i < two.length; i++){
table[two[i] - 'a']++;
}

for(int i = 0; i < one.length; i++){
table[one[i] - 'a']--;
if(table[one[i] - 'a'] < 0) return false;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HashTable