导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-383.Ransom Note

题目

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

翻译

给出一个赎金字条字符串,和另一个包含杂志上所有字母的字符串,编写函数,当可以用杂志字母组成赎金字符串时返回true,否则返回false。
杂志字符串中的每个字母在赎金字条中只能使用一次。
注意:你可以认为两个字符串都只包含小写字母。
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

因为都是小写字母,所以可以用一个长度为26的数组来记录每个字母出现次数:

1
2
3
4
5
6
7
8
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] chars = new int[26];
for (char c : magazine.toCharArray()) chars[c - 'a']++;
for (char c : ransomNote.toCharArray()) if (--chars[c - 'a'] < 0) return false;
return true;
}
}

Runtime: 14 ms