|
| 1 | +/** |
| 2 | + * [1897] Redistribute Characters to Make All Strings Equal |
| 3 | + * |
| 4 | + * You are given an array of strings words (0-indexed). |
| 5 | + * 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]. |
| 6 | + * Return true if you can make every string in words equal using any number of operations, and false otherwise. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * Input: words = ["abc","aabc","bc"] |
| 11 | + * Output: true |
| 12 | + * Explanation: Move the first 'a' in words[1] to the front of words[2], |
| 13 | + * to make words[1] = "abc" and words[2] = "abc". |
| 14 | + * All the strings are now equal to "abc", so return true. |
| 15 | + * |
| 16 | + * Example 2: |
| 17 | + * |
| 18 | + * Input: words = ["ab","a"] |
| 19 | + * Output: false |
| 20 | + * Explanation: It is impossible to make all the strings equal using the operation. |
| 21 | + * |
| 22 | + * |
| 23 | + * Constraints: |
| 24 | + * |
| 25 | + * 1 <= words.length <= 100 |
| 26 | + * 1 <= words[i].length <= 100 |
| 27 | + * words[i] consists of lowercase English letters. |
| 28 | + * |
| 29 | + */ |
| 30 | +pub struct Solution {} |
| 31 | + |
| 32 | +// problem: https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/ |
| 33 | +// discuss: https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/discuss/?currentPage=1&orderBy=most_votes&query= |
| 34 | + |
| 35 | +// submission codes start here |
| 36 | + |
| 37 | +impl Solution { |
| 38 | + pub fn make_equal(words: Vec<String>) -> bool { |
| 39 | + let mut hm = std::collections::HashMap::new(); |
| 40 | + |
| 41 | + for word in &words { |
| 42 | + for c in word.chars() { |
| 43 | + *hm.entry(c).or_insert(0) += 1; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + for letter in hm.values() { |
| 48 | + if *letter % words.len() != 0 { |
| 49 | + return false; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + true |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +// submission codes end |
| 58 | + |
| 59 | +#[cfg(test)] |
| 60 | +mod tests { |
| 61 | + use super::*; |
| 62 | + |
| 63 | + #[test] |
| 64 | + fn test_1897_example_1() { |
| 65 | + let words = vec_string!["abc", "aabc", "bc"]; |
| 66 | + |
| 67 | + let result = true; |
| 68 | + |
| 69 | + assert_eq!(Solution::make_equal(words), result); |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_1897_example_2() { |
| 74 | + let words = vec_string!["ab", "a"]; |
| 75 | + |
| 76 | + let result = false; |
| 77 | + |
| 78 | + assert_eq!(Solution::make_equal(words), result); |
| 79 | + } |
| 80 | +} |
0 commit comments