[LeetCode-383]Ransom Note(java)

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.