|
| 1 | +// Source : https://leetcode.com/problems/sorting-the-sentence/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-05-22 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * A sentence is a list of words that are separated by a single space with no leading or trailing |
| 8 | + * spaces. Each word consists of lowercase and uppercase English letters. |
| 9 | + * |
| 10 | + * A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging |
| 11 | + * the words in the sentence. |
| 12 | + * |
| 13 | + * For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" |
| 14 | + * or "is2 sentence4 This1 a3". |
| 15 | + * |
| 16 | + * Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original |
| 17 | + * sentence. |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: s = "is2 sentence4 This1 a3" |
| 22 | + * Output: "This is a sentence" |
| 23 | + * Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove |
| 24 | + * the numbers. |
| 25 | + * |
| 26 | + * Example 2: |
| 27 | + * |
| 28 | + * Input: s = "Myself2 Me1 I4 and3" |
| 29 | + * Output: "Me Myself and I" |
| 30 | + * Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the |
| 31 | + * numbers. |
| 32 | + * |
| 33 | + * Constraints: |
| 34 | + * |
| 35 | + * 2 <= s.length <= 200 |
| 36 | + * s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9. |
| 37 | + * The number of words in s is between 1 and 9. |
| 38 | + * The words in s are separated by a single space. |
| 39 | + * s contains no leading or trailing spaces. |
| 40 | + ******************************************************************************************************/ |
| 41 | + |
| 42 | +class Solution { |
| 43 | +public: |
| 44 | + string sortSentence(string s) { |
| 45 | + const int MAX_WORDS = 9; |
| 46 | + string ss[MAX_WORDS]; |
| 47 | + string word; |
| 48 | + for(int i=0; i<s.size(); i++){ |
| 49 | + char ch = s[i]; |
| 50 | + |
| 51 | + if (ch >='0' && ch <='9'){ |
| 52 | + ss[ch-'0'-1] = word; |
| 53 | + word = ""; |
| 54 | + }else if (ch != ' ') { |
| 55 | + word += ch; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + for(int i=1; i < MAX_WORDS; i++){ |
| 60 | + if (ss[i].size() <= 0 ) continue; |
| 61 | + ss[0] = ss[0] +" " + ss[i]; |
| 62 | + } |
| 63 | + return ss[0]; |
| 64 | + } |
| 65 | +}; |
0 commit comments