[LeetCode-383]Ransom Note(java)

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值