0
点赞
收藏
分享

微信扫一扫

leetcode之哈希表四: 检查两个字符串是否几乎相等

醉倾城1 2022-01-12 阅读 81

原题:

力扣icon-default.png?t=LBL2https://leetcode-cn.com/problems/check-whether-two-strings-are-almost-equivalent/submissions/

一、题目要求

如果两个字符串 word1 和 word2 中从 'a' 到 'z' 每一个字母出现频率之差都 不超过 3 ,那么我们称这两个字符串 word1 和 word2 几乎相等 。

给你两个长度都为 n 的字符串 word1 和 word2 ,如果 word1 和 word2 几乎相等 ,请你返回 true ,否则返回 false 。

一个字母 x 的出现 频率 指的是它在字符串中出现的次数。

示例 1:


示例 2:


示例 3:

提示:

n == word1.length == word2.length
1 <= n <= 100
word1 和 word2 都只包含小写英文字母。

二、解题

package com.leetcode.hash;

import java.util.HashMap;
import java.util.HashSet;

public class Solution16 {
    public static void main(String[] args) {
        //输入:word1 = "aaaa", word2 = "bccb"
        //输出:false
        //解释:字符串 "aaaa" 中有 4 个 'a' ,但是 "bccb" 中有 0 个 'a' 。
        //两者之差为 4 ,大于上限 3 。

        System.out.println(checkAlmostEquivalent("aaaa", "bccb" ));

    }

    public static boolean checkAlmostEquivalent(String word1, String word2) {
        HashMap<Character, Integer> map1 = new HashMap<Character, Integer>();
        HashMap<Character, Integer> map2 = new HashMap<Character, Integer>();
        HashSet<Character> set = new HashSet<Character>();

        for (int i = 0; i < word1.length(); i++) {
            char c = word1.charAt(i);
            map1.put(c, map1.get(c) == null ? 1 : map1.get(c) + 1);
            set.add(c);
        }

        for (int i = 0; i < word2.length(); i++) {
            char c = word2.charAt(i);
            map2.put(c, map2.get(c) == null ? 1 : map2.get(c) + 1);
            set.add(c);
        }

        for (char c : set) {
            int count1 = map1.get(c) == null? 0 : map1.get(c);
            int count2 = map2.get(c) == null? 0 : map2.get(c);
            if (Math.abs(count1 - count2) > 3) {
                return false;
            }
        }

        return true;
    }
}

三、运行结果

四、提交结果

 

举报

相关推荐

0 条评论