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.
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
题意:
现给出字符串str1和str2,判断str1是否能由str2中字符组成,str2中字符仅能出现一次,假设字符串中均只有小写字母。
分析:
比较直观的思路是:直接分别遍历str1和str2中各个字符出现的次数,如果str1中某个字符出现次数大于str2,显然不能;反之则可以。
先用两个数组分别存储字符串中a-z出现的次数,再依次比较两个数组中值,如果存在前者大于后者的情况,则返回false;否则,返回true。
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
//只有小写字母,分别申明保存2个字符串中26个字母依次出现的次数
int [] a=new int[26];
int [] b=new int[26];
//a[]遍历保存ransomNote中26个字母出现的次数
for(int i=0;i<ransomNote.length();i++){
a[ransomNote.charAt(i)-'a']++;
}
//b[]遍历保存magazine中26个字母出现的次数
for(int j=0;j<magazine.length();j++){
b[magazine.charAt(j)-'a']++;
}
//循环比较2个字符串中26个字母各自出现次数,如果数组a中某个字母出现次数大于b中对应字母的次数,则返回false
for(int k=0;k<26;k++){
if(a[k]>b[k])
return false;
}
return true;
}
}