当前位置:   article > 正文

LeetCode 1684. 统计一致字符串的数目_用hashset实现对字符串数组,字符串数量的统计

用hashset实现对字符串数组,字符串数量的统计

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

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

  1. class Solution {
  2. // 9:40
  3. Set<Character> set = new HashSet();
  4. boolean check(String w) {
  5. for (int i = 0; i < w.length(); i++) if (!set.contains(w.charAt(i))) return false;
  6. return true;
  7. }
  8. public int countConsistentStrings(String allowed, String[] words) {
  9. int ans = 0;
  10. for (int i = 0; i < allowed.length(); i++) set.add(allowed.charAt(i));
  11. for (var w: words) if (check(w)) ans++;
  12. return ans;
  13. }
  14. }

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

  1. class Solution {
  2. // 10:05
  3. boolean[] set = new boolean[26];
  4. boolean check(String w) {
  5. for (int i = 0; i < w.length(); i++) {
  6. if (!set[w.charAt(i) - 'a']) return false;
  7. }
  8. return true;
  9. }
  10. public int countConsistentStrings(String allowed, String[] words) {
  11. for (int i = 0; i < allowed.length(); i++) set[allowed.charAt(i) - 'a'] = true;
  12. int ans = 0;
  13. for (String w: words) if (check(w)) ans++;
  14. return ans;
  15. }
  16. }

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

  1. class Solution {
  2. int mask(String w) {
  3. int m = 0;
  4. for (int i = 0; i < w.length(); i++) m |= 1 << (w.charAt(i) - 'a');
  5. return m;
  6. }
  7. public int countConsistentStrings(String allowed, String[] words) {
  8. int m = mask(allowed);
  9. int ans = 0;
  10. for (var w: words) if ((m | mask(w)) == m) ans++;
  11. return ans;
  12. }
  13. }
  1. class Solution {
  2. public:
  3. // 10:20
  4. int mask(string s) {
  5. int m = 0;
  6. for (int i = 0; i < s.length(); i++) m |= 1 << (s[i] - 'a');
  7. return m;
  8. }
  9. int countConsistentStrings(string allowed, vector<string>& words) {
  10. int m = mask(allowed);
  11. int ans = 0;
  12. for (auto w: words) if ((m | mask(w)) == m) ans++;
  13. return ans;
  14. }
  15. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50315
推荐阅读
相关标签
  

闽ICP备14008679号