LeetCode 383 Ransom Note
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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。可以用两个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的主要内容,如果未能解决你的问题,请参考以下文章