首页 > 代码库 > leetcode_383 Ransom Note(String)
leetcode_383 Ransom Note(String)
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
给定两个字符串,判断前一个字符串能否由后一个字符串构成,后一个字符串中的字符只能使用一次。
solution1:定义一个长度为26的数组,对应26个字母
java中默认整数数组自动赋值为0
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { int[] arr=new int[26]; for(int i=0;i<magazine.length();i++){ arr[magazine.charAt(i)-‘a‘]++; } for(int i=0;i<ransomNote.length();i++){ if(--arr[ransomNote.charAt(i)-‘a‘]<0){ return false; } } return true; } }
solution2:hashmap
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { Map<Character, Integer> map= new HashMap<>(); for (char c:magazine.toCharArray()){ int count = magM.getOrDefault(c, 0)+1; map.put(c, count); } for (char c:ransomNote.toCharArray()){ int count = map.getOrDefault(c,0)-1; if (count<0) return false; map.put(c, count); } return true; } }
leetcode_383 Ransom Note(String)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。