You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1800-1899/1859.Sorting the Sentence/README_EN.md
+7-31
Original file line number
Diff line number
Diff line change
@@ -83,13 +83,9 @@ tags:
83
83
84
84
### Solution 1: String Splitting
85
85
86
-
First, we split the string $s$ by spaces to get the string array $words$. Then, we create a string array $ans$ of length $|words|$ to store the answer.
86
+
First, we split the string $s$ by spaces to get the array of strings $\textit{ws}$. Then, we iterate through the array $\textit{ws}$, subtracting the character '1' from the last character of each word to get the result as the index of the word. We take the prefix of the word as the content of the word. Finally, we concatenate the words in index order.
87
87
88
-
Next, we iterate over each string $w$ in the string array $words$, find the position $i$ represented by the last character of $w$, then take the first $|w|-1$ characters of $w$ as the new string $w'$, and place $w'$ in the $i$th position of the array $ans$.
89
-
90
-
Finally, we join the array $ans$ into a string by spaces, which is the answer.
91
-
92
-
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$.
88
+
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$.
93
89
94
90
<!-- tabs:start -->
95
91
@@ -98,9 +94,11 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is
98
94
```python
99
95
classSolution:
100
96
defsortSentence(self, s: str) -> str:
101
-
ws = [(w[:-1], int(w[-1])) for w in s.split()]
102
-
ws.sort(key=lambdax: x[1])
103
-
return''.join(w for w, _ in ws)
97
+
ws = s.split()
98
+
ans = [None] *len(ws)
99
+
for w in ws:
100
+
ans[int(w[-1]) -1] = w[:-1]
101
+
return"".join(ans)
104
102
```
105
103
106
104
#### Java
@@ -193,26 +191,4 @@ var sortSentence = function (s) {
0 commit comments