您的位置:首页 > 其它

【LeetCode】383.Ransom Note(Easy)解题报告

2018-02-27 19:23 501 查看
【LeetCode】383.Ransom Note(Easy)解题报告

题目地址:https://leetcode.com/problems/ransom-note/description/

题目描述:

  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


Solution:

//是否能够从第二个字符串中提取信息到第一个字符串。count或者hashmap。此题不需连续,只需要个数够即可。
//time : O(n)
//space : O(1)
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] count = new int[26];
for(int i=0 ; i<magazine.length() ; i++){
count[magazine.charAt(i)-'a']++;
}
for(int i=0 ; i<ransomNote.length() ; i++){
if(--count[ransomNote.charAt(i) - 'a']<0){
return false;
}
}
return true;
}
}


Date:2018年2月27日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  array leetcode