【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.
Solution:
Date:2018年2月27日
题目地址: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日
相关文章推荐
- LeetCode解题报告 383. Ransom Note [easy]
- LeetCode解题报告 101. Symmetric Tree [easy]
- 【LeetCode】206.Reverse Linked List(Easy)解题报告
- LeetCode解题报告 112. Path Sum [easy]
- [Leetcode] 383. Ransom Note 解题报告
- 【LeetCode】234.Palindrome Linked List(Easy)解题报告
- 【LeetCode】448.Find All Numbers Disappeared in an Array(Easy)解题报告
- 【LeetCode】141.Linked List Cycle(easy)解题报告
- LeetCode解题报告 70. Climbing Stairs [easy]
- 【LeetCode】112.Path Sum(Easy)解题报告
- LeetCode解题报告 1. Two Sum[easy]
- 【LeetCode】687.Longest Univalue Path(Easy)解题报告
- 【LeetCode】107.Binary Tree Level Order Traversal II(Easy)解题报告
- 【LeetCode】653.Two Sum IV - Input is a BST(Easy)解题报告
- 【LeetCode】270.Closest Binary Search Tree Value(Easy)解题报告
- 【LeetCode】160.Intersection of Two Linked Lists(Easy)解题报告
- 【LeetCode】257.Binary Tree Paths(Easy)解题报告
- LeetCode解题报告 107. Binary Tree Level Order Traversal II [easy]
- 【LeetCode】88.Merge Sorted Array(easy)解题报告
- LeetCode解题报告 455. Assign Cookies [easy]