LeetCode之Ransom Note (Java+C)

题意:
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

题意确实很绕,表示没看明白,后来上网翻译了下才理解了,可以很简单的理解为:前面的字符串ransomNote能否完全由后面的字符串magazine的字符所组成(都只考虑为小写字母情况)

Java代码:

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        char[] ransoms = ransomNote.toCharArray();
        char[] magazines = magazine.toCharArray();
        for(int i = 0; i < ransoms.length; i++) {
            for(int j = 0; j < magazines.length; j++) {
                if(ransoms[i] == magazines[j]) {
                    ransoms[i] = 0;
                    magazines[j] = 0;
                    break;
                }
            }
        }
        for(char r : ransoms) {
            if(r != 0) return false;
        }
        return true;
    }
}

C代码:

bool canConstruct(char* ransomNote, char* magazine) {
    int ransomLen = sizeof(ransomNote);
    int magazineLen = sizeof(magazine);
    for(int i = 0; i < ransomLen; i++) {
        for(int j = 0; j < magazineLen; j++) {
            if(ransomNote[i] == magazine[j]) {
                ransomNote[i] = 0;
                magazine[j] = 0;
                break;
            }
        }
    }
    for(int i = 0; i < ransomLen; i++) {
        if(ransomNote[i] != 0)
            return false;
    }
    return true;
}

解题思路:遍历数组,一一比对,相同的话,相应两数组的元素均置零!最后重新遍历ransomNote数组,如果存在非零元素,说明不符合要求,返回false,反之返回true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值