383. Ransom Note
2016-08-19 16:12
211 查看
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.
思路:
检查前面的勒索信是否可以由后面的字符串拼接而成
public boolean canConstruct(String ransomNote, String magazine) {
int[] map = new int[26];
for (int i = 0; i < magazine.length(); i++) {
map[magazine.charAt(i) - 'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if (map[ransomNote.charAt(i) - 'a'] > 0) {
map[ransomNote.charAt(i) - 'a']--;
} else {
return false;
}
}
return true;
}
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 boolean canConstruct(String ransomNote, String magazine) {
int[] map = new int[26];
for (int i = 0; i < magazine.length(); i++) {
map[magazine.charAt(i) - 'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if (map[ransomNote.charAt(i) - 'a'] > 0) {
map[ransomNote.charAt(i) - 'a']--;
} else {
return false;
}
}
return true;
}
相关文章推荐
- 383. Ransom Note(map容器)
- LeetCode OJ-383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode383. Ransom Note
- LeetCode383. Ransom Note优雅解法(线性时间复杂度)
- 383. Ransom Note
- Leetcode383. Ransom Note
- LeetCode解题报告 383. Ransom Note [easy]
- 383. Ransom Note 难度:easy
- 383. Ransom Note [LeetCode]
- [LeetCode]383. Ransom Note(赎金票据)
- oj383. Ransom Note
- [leetcode]: 383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- LeetCode 383. Ransom Note
- 383. Ransom Note
- LeetCode 383. Ransom Note 解题报告
- Leetcode 383. Ransom Note 构造字符串 解题报告
- 383. Ransom Note