返回介绍

solution / 1800-1899 / 1897.Redistribute Characters to Make All Strings Equal / README_EN

发布于 2024-06-17 01:03:13 字数 3935 浏览 0 评论 0 收藏 0

1897. Redistribute Characters to Make All Strings Equal

中文文档

Description

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.

Solutions

Solution 1

class Solution:
  def makeEqual(self, words: List[str]) -> bool:
    counter = Counter()
    for word in words:
      for c in word:
        counter[c] += 1
    n = len(words)
    return all(count % n == 0 for count in counter.values())
class Solution {
  public boolean makeEqual(String[] words) {
    int[] counter = new int[26];
    for (String word : words) {
      for (char c : word.toCharArray()) {
        ++counter[c - 'a'];
      }
    }
    int n = words.length;
    for (int i = 0; i < 26; ++i) {
      if (counter[i] % n != 0) {
        return false;
      }
    }
    return true;
  }
}
class Solution {
public:
  bool makeEqual(vector<string>& words) {
    vector<int> counter(26, 0);
    for (string word : words) {
      for (char c : word) {
        ++counter[c - 'a'];
      }
    }
    int n = words.size();
    for (int count : counter) {
      if (count % n != 0) return false;
    }
    return true;
  }
};
func makeEqual(words []string) bool {
  counter := [26]int{}
  for _, word := range words {
    for _, c := range word {
      counter[c-'a']++
    }
  }
  n := len(words)
  for _, count := range counter {
    if count%n != 0 {
      return false
    }
  }
  return true
}
function makeEqual(words: string[]): boolean {
  let n = words.length;
  let letters = new Array(26).fill(0);
  for (let word of words) {
    for (let i = 0; i < word.length; ++i) {
      ++letters[word.charCodeAt(i) - 97];
    }
  }

  for (let i = 0; i < letters.length; ++i) {
    if (letters[i] % n != 0) {
      return false;
    }
  }
  return true;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文