Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

383. Ransom Note #143

Open
Tcdian opened this issue May 3, 2020 · 1 comment
Open

383. Ransom Note #143

Tcdian opened this issue May 3, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 3, 2020

383. Ransom Note

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

Example

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

Note

  • 你可以假设两个字符串均只含有小写字母。
@Tcdian
Copy link
Owner Author

Tcdian commented May 3, 2020

Solution

  • JavaScript Solution
/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
    const cache = new Array(26).fill(0);
    
    for (let i = 0; i < magazine.length; i++) {
        cache[magazine.charCodeAt(i) - 97] += 1;
    }
    for (let i = 0; i < ransomNote.length; i++) {
        const letterCode = ransomNote.charCodeAt(i) - 97;
        if (cache[letterCode] < 1) {
            return false;
        } else {
            cache[letterCode] -= 1;
        }
    }
    return true;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant