zoukankan      html  css  js  c++  java
  • [LeetCode] 1897. Redistribute Characters to Make All Strings Equal

    You are given an array of strings words (0-indexed).

    In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].

    Return true if you can make every string in words equal using any number of operations, and false otherwise.

    Example 1:

    Input: words = ["abc","aabc","bc"]
    Output: true
    Explanation: Move the first 'a' in words[1] to the front of words[2],
    to make words[1] = "abc" and words[2] = "abc".
    All the strings are now equal to "abc", so return true.
    

    Example 2:

    Input: words = ["ab","a"]
    Output: false
    Explanation: It is impossible to make all the strings equal using the operation.

    Constraints:

    • 1 <= words.length <= 100
    • 1 <= words[i].length <= 100
    • words[i] consists of lowercase English letters.

    重新分配字符使所有字符串都相等。

    给你一个字符串数组 words(下标 从 0 开始 计数)。

    在一步操作中,需先选出两个 不同 下标 i 和 j,其中 words[i] 是一个非空字符串,接着将 words[i] 中的 任一 字符移动到 words[j] 中的 任一 位置上。

    如果执行任意步操作可以使 words 中的每个字符串都相等,返回 true ;否则,返回 false 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/redistribute-characters-to-make-all-strings-equal
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是用 hashmap 统计一下所有单词中出现过的所有字母的出现次数,然后用每个字母的次数去对 words.length 取模,如果有任何一个单词的取模结果不为0,说明这个字母无法被平均分配到每个单词中,就返回 false。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public boolean makeEqual(String[] words) {
     3         HashMap<Character, Integer> map = new HashMap<>();
     4         for (String w : words) {
     5             for (char c : w.toCharArray()) {
     6                 map.put(c, map.getOrDefault(c, 0) + 1);
     7             }
     8         }
     9 
    10         int len = words.length;
    11         for (Character letter : map.keySet()) {
    12             int count = map.get(letter);
    13             if (count % len != 0) {
    14                 return false;
    15             }
    16         }
    17         return true;
    18     }
    19 }

    LeetCode 题目总结

  • 相关阅读:
    00-03.kaliLinux-vi粘贴复制功能配置
    00-02.kaliLinux-配置SSH服务
    00-01.Kali Linux 2020.1修改root用户密码
    Web设计色彩(转载)
    Inno Setup区段之Language篇
    Inno Setup区段之Setup篇
    IE无法获取到input框的值
    Inno Setup之常量篇
    Inno Setup之概念篇
    网络不通排查
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14883801.html
Copyright © 2011-2022 走看看