统计相似字符串对的数目

class Solution {
    public int similarPairs(String[] words) {
        int count = 0;
        for (int i = 0; i < words.length; i++) {
            for (int j = i + 1; j < words.length; j++) {
                if (toCharSet(words[i]).equals(toCharSet(words[j]))) {
                    count++;
                }
            }
        }
        return count;
    }
    private Set<Character> toCharSet(String s) {
        Set<Character> charSet = new HashSet<>();
        for (char c : s.toCharArray()) {
            charSet.add(c);
        }
        return charSet;
    }
}
  1. 变量初始化

    • int count = 0;count 用于记录相似对的数量,初始值为 0。

  2. 双重循环遍历字符串数组

    • for (int i = 0; i < words.length; i++):外层循环遍历数组中的每一个字符串。

    • for (int j = i + 1; j < words.length; j++):内层循环从当前字符串的下一个字符串开始遍历,避免重复比较。

    • if (toCharSet(words[i]).equals(toCharSet(words[j]))):调用 toCharSet 方法将两个字符串转换为字符集合,并比较这两个集合是否相等。

      • 如果相等,说明这两个字符串是相似对,count 加 1。

  3. toCharSet 方法

    • private Set<Character> toCharSet(String s):这是一个辅助方法,用于将字符串 s 转换为字符集合。

    • Set<Character> charSet = new HashSet<>();:创建一个 HashSet 来存储字符。

    • for (char c : s.toCharArray()):遍历字符串中的每一个字符。

    • charSet.add(c);:将字符添加到集合中。由于 HashSet 会自动去重,因此集合中只包含唯一的字符。

    • return charSet;:返回字符集合。

  4. 返回结果

    • return count;:最终返回相似对的数量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值