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("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
第一种方法:
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
char[] noteArr = new char[ransomNote.length()];
noteArr = ransomNote.toCharArray();
for (int i = 0; i < noteArr.length; i++) {
if (magazine.indexOf(noteArr[i]) == -1) return false;
else {
int position = magazine.indexOf(noteArr[i]);
String before = magazine.substring(0, position);
String after = magazine.substring(position+1, magazine.length());
magazine = before.concat(after);
}
}
return true;
}
}
第二种方法:
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
char[] noteArr = new char[ransomNote.length()];
noteArr = ransomNote.toCharArray();
char[] magazineArr = new char[magazine.length()];
magazineArr = magazine.toCharArray();
// int数组默认会初始化为全为0
int[] noteLetter = new int[26];
int[] magazineLetter = new int[26];
for (int i = 0; i < noteArr.length; i++) {
int position = noteArr[i] - 'a';
noteLetter[position]++;
}
for (int i = 0; i < magazineArr.length; i++) {
int position = magazineArr[i] - 'a';
magazineLetter[position]++;
}
for (int i = 0; i < 26; i++) {
if (noteLetter[i] != 0 && noteLetter[i] > magazineLetter[i]) return false;
}
return true;
}
}