LeetCode之Ransom Note
【摘要】 1、题目
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 fro...
1、题目
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
2、代码实现
-
public class Solution {
-
public boolean canConstruct(String ransomNote, String magazine) {
-
if (magazine == null)
-
return false;
-
if (ransomNote == null)
-
return false;
-
if (ransomNote.length() == 0 && magazine.length() == 0)
-
return true;
-
List<Character> list = new ArrayList<Character>();
-
for (char c : magazine.toCharArray()) {
-
list.add(Character.valueOf(c));
-
}
-
if (ransomNote.length() == magazine.length()) {
-
for (int i = 0; i < ransomNote.length(); i++) {
-
if (!list.remove(Character.valueOf(ransomNote.charAt(i)))) {
-
return false;
-
}
-
}
-
return true;
-
} else {
-
for (int i = 0; i < ransomNote.length(); i++) {
-
if (!list.remove(Character.valueOf(ransomNote.charAt(i)))) {
-
return false;
-
}
-
}
-
if (list.size() > 0) {
-
return true;
-
}
-
}
-
return false;
-
}
-
}
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/68485900
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)