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.
即判斷 ransomNote 是否可以通過magazine中的字母組成,其中 magazine 中的字母不考慮順序,即只要有這個字母就行。注意的是 magazine 中每個字母只能用一次。
1. Comparing the character in ransomNote with the magazine directly. Obviously, nest loop has poor complexity. So I PRopose an easy-understand solution with Listwhich is faster than Map in sulution 2.
2. Using a certain structure to store the count of every character. For example, usingarrayand Map. This solution is so interesting and clever. And I also learn some basis of java.
1. 循環的簡介寫法,不需要數組下標 for (char c : str.toCharArray())
2. 數組下標 arr[c-'a']++;
3. Map 的學習
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { char[] rArray = ransomNote.toCharArray(); char[] mArray = magazine.toCharArray(); List<Character> rlist = new ArrayList<Character>(); for(int i = 0; i<magazine.length(); i++) rlist.add(mArray[i]); for(int i = 0; i<ransomNote.length(); i++){ if(rlist.contains(rArray[i])) rlist.remove(rlist.indexOf(rArray[i])); else return false; } return true; }}方法2:
—— Array
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { int[] arr = new int[26]; // method-1 for(char c: magazine.toCharArray()) arr[c-'a']++; for(char c: ransomNote.toCharArray()) if(--arr[c-'a'] < 0) return false; /* // method-2 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; }}—— Map
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { // method-3 Map<Character, Integer> map = new HashMap<>(); for(char c: magazine.toCharArray()){ int count = map.containsKey(c) ? map.get(c)+1 : 1; map.put(c, count); } for(char c: ransomNote.toCharArray()){ int newCount = map.containsKey(c) ? map.get(c)-1 : -1; if(newCount == -1) return false; map.put(c, newCount); } return true; }}方法2 中method-1 最快,其次method-2,用Map 比List 還慢。
新聞熱點
疑難解答