java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java C++统计一致字符串数目

Java C++题解leetcode 1684统计一致字符串的数目示例

作者:AnjaVon

这篇文章主要为大家介绍了Java C++题解leetcode 1684统计一致字符串的数目示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

题目

题目要求

思路:模拟

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;
    }
}

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;
    }
};

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
    }
}

以上就是Java C++题解leetcode 1684统计一致字符串的数目示例的详细内容,更多关于Java C++统计一致字符串数目的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文