RansomNoteOPT [source code]

public class RansomNoteOPT {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] ch = new int[26];
        for (char c : magazine.toCharArray()) {
            ch[c - 'a']++;
        }

        for (char c : ransomNote.toCharArray()) {
            if (--ch[c - 'a'] < 0) return false;
        }
        return true;
    }
}

这个是 submission 最优解, 12ms, 98%.
总体思路其实跟我的代码没有什么区别, 不过速度却快了很多. 不纠结了;


Problem Description

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
Difficulty:Easy
Category:Algorithms
Acceptance:46.91%
Contributor: LeetCode
Companines
Apple
Related Topics
string

results matching ""

    No results matching ""