LeetCode之Ransom Note

91 阅读1分钟

1、题目

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

 

2、代码实现

public class Solution {
    	public  boolean canConstruct(String ransomNote, String magazine) {
		   if (magazine == null)
			   return false;
		   if (ransomNote == null)
			   return false;
		   if (ransomNote.length() == 0 && magazine.length() == 0) 
			   return true;
		   List<Character> list = new ArrayList<Character>();
		   for (char c : magazine.toCharArray()) {
			   list.add(Character.valueOf(c));
		   }
		   if (ransomNote.length() == magazine.length()) {
			   for (int i = 0; i < ransomNote.length(); i++) {
				   if (!list.remove(Character.valueOf(ransomNote.charAt(i)))) {
					   return false;
				   }
			   }
			   return true;
		   } else {
			   for (int i = 0; i < ransomNote.length(); i++) {
				   if (!list.remove(Character.valueOf(ransomNote.charAt(i)))) {
					   return false;
				   }
			   }
			   if (list.size() > 0) {
				   return true;
			   }
		   }
	       return false;
	}
}