|
6 | 6 |
|
7 | 7 | <p>A <strong>sentence</strong> is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.</p>
|
8 | 8 |
|
9 |
| - |
10 |
| - |
11 | 9 | <p>A sentence can be <strong>shuffled</strong> by appending the <strong>1-indexed word position</strong> to each word then rearranging the words in the sentence.</p>
|
12 | 10 |
|
13 |
| - |
14 |
| - |
15 | 11 | <ul>
|
16 | 12 | <li>For example, the sentence <code>"This is a sentence"</code> can be shuffled as <code>"sentence4 a3 is2 This1"</code> or <code>"is2 sentence4 This1 a3"</code>.</li>
|
17 | 13 | </ul>
|
18 | 14 |
|
19 |
| - |
20 |
| - |
21 | 15 | <p>Given a <strong>shuffled sentence</strong> <code>s</code> containing no more than <code>9</code> words, reconstruct and return <em>the original sentence</em>.</p>
|
22 | 16 |
|
23 |
| - |
24 |
| - |
25 | 17 | <p> </p>
|
26 | 18 |
|
27 | 19 | <p><strong>Example 1:</strong></p>
|
28 | 20 |
|
29 |
| - |
30 |
| - |
31 | 21 | <pre>
|
32 | 22 |
|
33 | 23 | <strong>Input:</strong> s = "is2 sentence4 This1 a3"
|
|
38 | 28 |
|
39 | 29 | </pre>
|
40 | 30 |
|
41 |
| - |
42 |
| - |
43 | 31 | <p><strong>Example 2:</strong></p>
|
44 | 32 |
|
45 |
| - |
46 |
| - |
47 | 33 | <pre>
|
48 | 34 |
|
49 | 35 | <strong>Input:</strong> s = "Myself2 Me1 I4 and3"
|
|
54 | 40 |
|
55 | 41 | </pre>
|
56 | 42 |
|
57 |
| - |
58 |
| - |
59 | 43 | <p> </p>
|
60 | 44 |
|
61 | 45 | <p><strong>Constraints:</strong></p>
|
62 | 46 |
|
63 |
| - |
64 |
| - |
65 | 47 | <ul>
|
66 | 48 | <li><code>2 <= s.length <= 200</code></li>
|
67 | 49 | <li><code>s</code> consists of lowercase and uppercase English letters, spaces, and digits from <code>1</code> to <code>9</code>.</li>
|
|
77 | 59 | ### **Python3**
|
78 | 60 |
|
79 | 61 | ```python
|
80 |
| - |
| 62 | +class Solution: |
| 63 | + def sortSentence(self, s: str) -> str: |
| 64 | + words = s.split(' ') |
| 65 | + arr = [None] * len(words) |
| 66 | + for word in words: |
| 67 | + idx = int(word[-1]) - 1 |
| 68 | + arr[idx] = word[:-1] |
| 69 | + return ' '.join(arr) |
81 | 70 | ```
|
82 | 71 |
|
83 | 72 | ### **Java**
|
84 | 73 |
|
85 | 74 | ```java
|
86 |
| - |
| 75 | +class Solution { |
| 76 | + public String sortSentence(String s) { |
| 77 | + String[] words = s.split(" "); |
| 78 | + String[] arr = new String[words.length]; |
| 79 | + for (String word : words) { |
| 80 | + int idx = word.charAt(word.length() - 1) - '0' - 1; |
| 81 | + arr[idx] = word.substring(0, word.length() - 1); |
| 82 | + } |
| 83 | + return String.join(" ", arr); |
| 84 | + } |
| 85 | +} |
87 | 86 | ```
|
88 | 87 |
|
89 | 88 | ### **...**
|
|
0 commit comments