|
| 1 | +// Source : https://leetcode.com/problems/short-encoding-of-words/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2020-10-02 |
| 4 | +/***************************************************************************************************** |
| 5 | + * |
| 6 | + * Given a list of words, we may encode it by writing a reference string S and a list of indexes A. |
| 7 | + * |
| 8 | + * For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" |
| 9 | + * and indexes = [0, 2, 5]. |
| 10 | + * |
| 11 | + * Then for each index, we will recover the word by reading from the reference string from that index |
| 12 | + * until we reach a "#" character. |
| 13 | + * |
| 14 | + * What is the length of the shortest reference string S possible that encodes the given words? |
| 15 | + * |
| 16 | + * Example: |
| 17 | + * |
| 18 | + * Input: words = ["time", "me", "bell"] |
| 19 | + * Output: 10 |
| 20 | + * Explanation: S = "time#bell#" and indexes = [0, 2, 5]. |
| 21 | + * |
| 22 | + * Note: |
| 23 | + * |
| 24 | + * 1 <= words.length <= 2000. |
| 25 | + * 1 <= words[i].length <= 7. |
| 26 | + * Each word has only lowercase letters. |
| 27 | + * |
| 28 | + ******************************************************************************************************/ |
| 29 | +class Solution { |
| 30 | +public: |
| 31 | + static bool comp(string a,string b){ |
| 32 | + return a.size() < b.size(); |
| 33 | + } |
| 34 | + int minimumLengthEncoding(vector<string>& words) { |
| 35 | + sort(words.begin(),words.end(),comp); |
| 36 | + int ans = 0; |
| 37 | + int count = 0; |
| 38 | + unordered_map<string,int> M; |
| 39 | + for(int i = 0 ; i < words.size() ; i++){ |
| 40 | + string temp = ""; |
| 41 | + for(int k = words[i].size() - 1 ; k >= 0 ; k--){ |
| 42 | + temp = words[i][k] + temp; |
| 43 | + M[temp]++; |
| 44 | + } |
| 45 | + } |
| 46 | + for(int i = 0 ; i < words.size() ; i++){ |
| 47 | + ans = ans + words[i].size(); |
| 48 | + count++; |
| 49 | + if(M[words[i]] > 1){ |
| 50 | + ans = ans - words[i].size(); |
| 51 | + count--; |
| 52 | + M[words[i]]--; |
| 53 | + } |
| 54 | + } |
| 55 | + return ans + count; |
| 56 | + } |
| 57 | +}; |
0 commit comments