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
给定一个任意的赎金票据字符串和另一个字符串,包含所有杂志的字母,写一个函数,如果可以从杂志中构建赎金票据,则返回true; 否则会返回false。
杂志字符串中的每个字母只能在您的赎金笔记中使用一次。就是前面的字符串可以由后面字符串中的字母挑选组成,且字母只能使用一次。
注意:
您可以假设两个字符串只包含小写字母。
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
思路:
先判断m是否包含r,不包含则转字符数组,分别排序,从头开始对比,sum为r的长度,若相同sum减一,角标均增加,若m[i]>r[i],r角标加一,否则m角标加一,注意判断r的角标是否到达最大,否则会数组越界。最后通过判断sum大小返回结果。
public boolean canConstruct(String ransomNote, String magazine) {
if(magazine.contains(ransomNote)) return true;
else{
char[] r = ransomNote.toCharArray();
char[] m = magazine.toCharArray();
int sum = r.length;
Arrays.sort(r);
Arrays.sort(m);
int j = 0;
for(int i=0; i<m.length; i++){
if(m[i] == r[j]) {
sum--;
j++;
if(j == r.length) break;
continue;
}else if(m[i]-r[j] >0){
j++;
if(j == r.length) break;
}
}
if(sum == 0) return true;
else return false;
}
}