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
判断字典里的字符能不能组成ransom note。
O(n)解法:
使用索引数组index存储每个字符在字典里找的值,使用方法indexOf(char ch, int offset),更新index数组,如果某次查找出现-1,即找不到,这是就可判断false了
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if(ransomNote=="")
return true;
if(magazine=="")
return false;
int len=ransomNote.length();
int[] index = new int[128];
for(int i=0;i<len;i++){
char cu=ransomNote.charAt(i);
int result=magazine.indexOf(cu,index[cu]);
if(result!=-1)
index[cu]=result+1;
else
return false;
}
return true;
}
}