leetcode1160. 拼寫單詞

給你一份『詞彙表』(字符串數組) words 和一張『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼寫出 words 中的某個『單詞』(字符串),那麼我們就認爲你掌握了這個單詞。

注意:每次拼寫時,chars 中的每個字母都只能用一次。

返回詞彙表 words 中你掌握的所有單詞的 長度之和。

示例 1:

輸入:words = ["cat","bt","hat","tree"], chars = "atach"
輸出:6
解釋: 
可以形成字符串 "cat""hat",所以答案是 3 + 3 = 6

示例 2:

輸入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
輸出:10
解釋:
可以形成字符串 "hello""world",所以答案是 5 + 5 = 10

提示:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • 所有字符串中都僅包含小寫英文字母

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

完整代碼

基本思想:
查找每一個單詞中的每一個字母是否在字母表中出現,由於字母表中的字母不允許重複出現,所以在查找到該字母時,將該字母刪掉。

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        if(words.size() == 0 || chars.size() == 0)
            return 0;
        int res = 0;
        for(int i = 0; i < words.size(); ++i){
            string temp = chars;
            bool flag = false;
            for(int j = 0; j < words[i].size(); ++j){
                int pos = temp.find(words[i][j]);
                if(pos < 0 || pos >= temp.size()){
                    flag = true;
                    break;
                }
                temp.erase(pos, 1);
            }
            if(!flag)
                res += words[i].size();
        }
        return res;
    }
};

解法二:參考別人的想法
統計字母表中每個單詞的每個字母出現的次數,統計每個單詞中每個字母出現的次數,如果每個單詞中的每個字母出現的次數小於等於字母表中的每個字母出現的次數,那麼該單詞可以拼寫
注意:這裏可以用map,unordered_map實現,也可以用長度爲26的整型數組實現,因爲題目中明確說明了所有字符串中都僅包含小寫英文字母

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        if(words.size() == 0 || chars.size() == 0)
            return 0;
        int res = 0;
        //1.統計字母表中的每個字母出現的次數。
        vector<int> count(26, 0);
        for(auto c : chars)
            ++count[c - 'a'];
        for(auto word : words){
            vector<int> temp(26, 0);
            for(auto c : word)
                ++temp[c - 'a'];
            bool flag = false;
            for(int i = 0; i < 26; ++i){
                if(temp[i] > count[i]){
                    flag = true;
                    break;
                }
            }
            if(!flag)
                res += word.size();
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章