欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > 【Leetcode 每日一题】2506. 统计相似字符串对的数目

【Leetcode 每日一题】2506. 统计相似字符串对的数目

2025/2/24 3:31:20 来源:https://blog.csdn.net/2401_88859777/article/details/145799200  浏览:    关键词:【Leetcode 每日一题】2506. 统计相似字符串对的数目

问题背景

给你一个下标从 0 0 0 开始的字符串数组 w o r d s words words
如果两个字符串由相同的字符组成,则认为这两个字符串 相似

  • 例如,“abca” 和 “cba” 相似,因为它们都由字符 ‘a’、‘b’、‘c’ 组成。
  • 然而,“abacba” 和 “bcfd” 不相似,因为它们不是相同字符组成的。

请你找出满足字符串 w o r d s [ i ] words[i] words[i] w o r d s [ j ] words[j] words[j] 相似的下标对 ( i , j ) (i, j) (i,j),并返回下标对的数目,其中 0 ≤ i < j ≤ w o r d s . l e n g t h − 1 0 \le i \lt j \le words.length - 1 0i<jwords.length1

数据约束

  • 1 ≤ w o r d s . l e n g t h ≤ 100 1 \le words.length \le 100 1words.length100
  • 1 ≤ w o r d s [ i ] . l e n g t h ≤ 100 1 \le words[i].length \le 100 1words[i].length100
  • w o r d s [ i ] words[i] words[i] 仅由小写英文字母组成

解题过程

想到了字符串映射和字符串哈希,没想到用位运算来进行压缩存储。统计数量的做法,参考 好数对数目 就可以了。

具体实现

class Solution {public int similarPairs(String[] words) {Map<Integer, Integer> count = new HashMap<>();int res = 0;for (String word : words) {int mask = 0;for (char c : word.toCharArray()) {mask |= 1 << (c - 'a');}int cur = count.getOrDefault(mask, 0);res += cur;count.put(mask, cur + 1);}return res;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词