leetcode [#383]

目录

题目

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.

Example:
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

Note:
You may assume that both strings contain only lowercase letters.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int len1 = ransomNote.length();
int len2 = magazine.length();
if(len1 > len2) return false;
boolean result = true;
List<String> list = new ArrayList<>();
for(int k = 0; k < len2; k++){
list.add(String.valueOf(magazine.charAt(k)));
}
for(int i = 0; i < len1; i++){
if(!list.remove(String.valueOf(ransomNote.charAt(i)))){
result = false;
break;
}
}
return result;
}
}

注意事项

  1. 先判断特殊情况,如果magazine的长度比ransomNote小,那么一定不能组成结果。
  2. 将magazine的每个字符存入list备用。
  3. 遍历ransomNote,将每个字符从list中弹出,如果成功,证明list中有这个字符,也就是能作为构成ransomNote的一个字符,如果弹出失败,说明没有这个字符,返回false即可。