⬆︎
×

[LC] 1160 Find Words That Can Be Formed by Characters

Hyplus目录

Java

/**
 * <a href="https://leetcode.cn/problems/find-words-that-can-be-formed-by-characters/">Find Words That Can Be Formed by Characters</a>
 * 数组;哈希表;字符串;计数
 */
class Solution {
    public int countCharacters(String[] words, String chars) {
        int[] charCounter = getCharCounter(chars);

        int res = 0;
        for (String word : words) {
            int[] wordCount = getCharCounter(word);

            boolean canSpell = true;
            for (int i = 0; i < 26; i++) {
                if (charCounter[i] < wordCount[i]) {
                    canSpell = false;
                    break;
                }
            }
            if (canSpell) {
                res += word.length();
            }
        }
        return res;
    }

    private int[] getCharCounter(String chars) {
        int[] charCounter = new int[26];
        for (int i = 0; i < chars.length(); i++) {
            char ch = chars.charAt(i);
            charCounter[ch - 'a']++;
        }
        return charCounter;
    }
}

C++

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution {
public:
    int countCharacters(vector <string> &words, string chars) {
        int res = 0;
        unordered_map<char, int> cnt;

        for (int i = 0; i < chars.size(); ++i) cnt[chars[i]]++;

        for (int i = 0; i < words.size(); ++i) {
            unordered_map<char, int> temp_cnt = cnt;
            bool success = true;
            for (int j = 0; j < words[i].size(); ++j) {
                if (!temp_cnt[words[i][j]]) {
                    success = false;
                    break;
                }
                temp_cnt[words[i][j]]--;
            }
            if (success) res += words[i].size();
        }

        return res;
    }
};

发表评论