LeetCode 1684. 统计一致字符串的数目

1684. 统计一致字符串的数目

【哈希】直接用HashSet,但是HashSet初始容量为16涉及到了扩容,所以效率略低一点。

class Solution {

    // 9:40

    Set<Character> set = new HashSet();
        
    boolean check(String w) {
        for (int i = 0; i < w.length(); i++) if (!set.contains(w.charAt(i))) return false;
        return true;
    }

    public int countConsistentStrings(String allowed, String[] words) {
        int ans = 0;
        for (int i = 0; i < allowed.length(); i++) set.add(allowed.charAt(i));
        for (var w: words) if (check(w)) ans++;
        return ans;
    }
}

【哈希】因为字母只有26个,所以可以用一个定长的数组来代替哈希表。

class Solution {

    // 10:05
    
    boolean[] set = new boolean[26];
        
    boolean check(String w) {
        for (int i = 0; i < w.length(); i++) {
            if (!set[w.charAt(i) - 'a']) return false;
        }
        return true;
    } 

    public int countConsistentStrings(String allowed, String[] words) {
        for (int i = 0; i < allowed.length(); i++) set[allowed.charAt(i) - 'a'] = true;
        int ans = 0;
        for (String w: words) if (check(w)) ans++;
        return ans;
    }
}

【位运算】又是因为字母只有26个,所以可以用一个int的后面26位来保存这个信息。将原来的字符串编码,然后将两个编码后的哈希值进行或运算,如果跟之前的哈希值相同,说明没有引入新的位,也就是没有新出现的字母。

class Solution {

    int mask(String w) {
        int m = 0;
        for (int i = 0; i < w.length(); i++) m |= 1 << (w.charAt(i) - 'a');
        return m;
    }

    public int countConsistentStrings(String allowed, String[] words) {
        int m = mask(allowed);
        int ans = 0;
        for (var w: words) if ((m | mask(w)) == m) ans++;
        return ans;
    }
}
class Solution {
public:

    // 10:20

    int mask(string s) {
        int m = 0;
        for (int i = 0; i < s.length(); i++) m |= 1 << (s[i] - 'a');
        return m;
    }

    int countConsistentStrings(string allowed, vector<string>& words) {
        int m = mask(allowed);
        int ans = 0;
        for (auto w: words) if ((m | mask(w)) == m) ans++;
        return ans;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值