您的位置:首页 > 其它

LeetCode - 383. Ransom Note

2017-02-16 22:24 591 查看

题目:

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 的学习

Java程序实现:

方法1:直接比较 —— List

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 还慢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: