---
# System prepended metadata

title: 'Leetcode [No. 1897] Redistribute Characters to Make All Strings Equal (EASY)'
tags: [leetcode]

---

# Leetcode [No. 1897] Redistribute Characters to Make All Strings Equal (EASY)

## 題目

https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/

## 思路
+ 這個解法其實滿naive的，因為你有無限次的操作機會可以讓這幾個字串相等，所以你只要去計算每一個char出現的次數是否可以被words_size整除即可
```c++=
class Solution {
public:
    bool makeEqual(vector<string>& words) {
        // count every single char into map
        unordered_map<char,int> hashMap;
        int words_size = words.size();
        for(int i = 0 ;i < words_size; i++)
        {
            for (int j = 0 ; j < words[i].size(); j++)
            {
                hashMap[words[i][j]]++;
            }
        }

        for(auto& c: hashMap)
        {
            if(c.second % words_size != 0)
            {
                return false;
            }
        }
        return true;
    }
};
```

### 解法分析
+ time complexity: O(n)


### 執行結果

![image](https://hackmd.io/_uploads/r1e58Gpv6.png)

## 改良時間複雜度及寫法

+ 改用C++ iterator來取代原始的for迴圈
+ 加了一個更快得到解答的判斷式。

```C++=
class Solution {
public:
    bool makeEqual(vector<string>& words) {
        if(words.size() == 1)
        {
            return true;
        }

        // count every single char into array
        int alphabet_count[26] = {};
        int words_size = words.size();
        for(string & s: words)
        {
            for (char& c: s)
            {
                alphabet_count[c-'a']++;
            }
        }

        for(int& count: alphabet_count)
        {
            if(count % words_size != 0)
            {
                return false;
            }
        }
        return true;
    }
};
```

### 解法分析
+ time complexity: O(n)

### 執行結果
![image](https://hackmd.io/_uploads/Syxc1dzpDp.png)
