Java&C++题解与拓展——leetcode1684. 统计一致字符串的数目【么的新知识】

77 阅读1分钟
每日一题做题记录,参考官方和三叶的题解

题目要求

image.png

image.png

思路:模拟

  • 用一个哈希表记录可出现的字母,然后逐一遍历每个单词每个字母,符合条件则结果加一。

Java

class Solution {
    public int countConsistentStrings(String allowed, String[] words) {
        boolean[] hash = new boolean[26];
        for (var a : allowed.toCharArray())
            hash[a - 'a'] = true;
        int res = 0;
        stop : for (var word : words) {
            for (var w : word.toCharArray()) {
                if (!hash[w - 'a'])
                    continue stop;
            }
            res++;
        }
        return res;
    }
}
  • 时间复杂度:O(m+i=0n1words[i].length)O(m+\sum^{n-1}_{i=0}words[i].length),其中mmnn分别为allowedallowedwordswords的长度
  • 空间复杂度:O(m)O(m)

C++

class Solution {
public:
    int countConsistentStrings(string allowed, vector<string>& words) {
        int hash[26] = {0};
        for (auto a : allowed)
            hash[a - 'a'] = true;
        int res = 0;
        for (auto& word : words) {
            bool ok = true;
            for (auto w : word) {
                if (!hash[w - 'a']) {
                    ok = false;
                    continue;
                }
            }
            if (ok)
                res++;
        }
        return res;
    }

};
  • 时间复杂度:O(m+i=0n1words[i].size)O(m+\sum^{n-1}_{i=0}words[i].size),其中mmnn分别为allowedallowedwordswords的长度
  • 空间复杂度:O(m)O(m)

Rust

impl Solution {
    pub fn count_consistent_strings(allowed: String, words: Vec<String>) -> i32 {
        let mut hash = vec![false; 26];
        for a in allowed.as_bytes().iter() {
            hash[(a - b'a') as usize] = true;
        }
        let mut res = 0;
        for word in words {
            let mut ok = true;
            for w in word.as_bytes().iter() {
                if !hash[(w - b'a') as usize] {
                    ok = false;
                    continue;
                }
            }
            if ok {
                res += 1;
            }
        }
        res
    }
}
  • 时间复杂度:O(m+i=0n1words[i].len)O(m+\sum^{n-1}_{i=0}words[i].len),其中mmnn分别为allowedallowedwordswords的长度
  • 空间复杂度:O(m)O(m)

总结

  • 简单模拟题鸭~
  • 最近状态不行,要提高一下效率……

欢迎指正与讨论!