首页 > 代码库 > LeetCode 383 Ransom Note
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") -> falsecanConstruct("aa", "ab") -> falsecanConstruct("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 else21 return false;22 }23 24 return true;25 }26 }
LeetCode 383 Ransom Note
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。