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; }}