【LeetCode】383. Ransom Note 赎金信(Easy)(JAVA)
题目地址: https://leetcode.com/problems/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.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
- You may assume that both strings contain only lowercase letters.
题目大意
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)
注意:
- 你可以假设两个字符串均只含有小写字母。
解题方法
- 就是判断 ransomNote 的字符是否在 magazine 都有,而且 magazine 中字符不能重复使用
- 因为这一题的字符串只包含小写字母所以用一个长度 26 的一维数组存字母出现的次数; ransomNote 字母出现 -1, magazine字母出现 +1
- 最后判断下字母出现次数是否大于等于 0 即可
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote.length() > magazine.length()) return false;
int[] count = new int[26];
for (int i = 0; i < magazine.length(); i++) {
count[magazine.charAt(i) - 'a']++;
if (i < ransomNote.length()) count[ransomNote.charAt(i) - 'a']--;
}
for (int i = 0; i < count.length; i++) {
if (count[i] < 0) return false;
}
return true;
}
}
执行耗时:3 ms,击败了62.61% 的Java用户
内存消耗:38.7 MB,击败了70.26% 的Java用户