码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 383 Ransom Note

时间:2016-09-04 01:34:04      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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。可以用两个list(或者一个queue一个list,一个stack一个list,均可),将前者的字符串一个个从所属数据结构中剔除时,在后者的数据结构中找到对应字符并剔除,如果无法完成该操作,则视为false。

 

解法:

 1 import java.util.ArrayList;
 2 import java.util.Stack;
 3 
 4 public class Solution
 5 {
 6     public boolean canConstruct(String ransomNote, String magazine)
 7     {
 8         Stack<Character> stack = new Stack<>();
 9         ArrayList<Character> list = new ArrayList<>();
10 
11         for(char c: ransomNote.toCharArray())
12             stack.push(c);
13         for(char c: magazine.toCharArray())
14             list.add(c);
15 
16         while(!stack.isEmpty())
17         {
18             if(list.contains(stack.peek()))
19                 list.remove(stack.pop());
20             else
21                 return false;
22         }
23 
24         return true;
25     }
26 }

 

LeetCode 383 Ransom Note

标签:

原文地址:http://www.cnblogs.com/wood-python/p/5838442.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!