We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 0dc1fc8 commit 0d08dd8Copy full SHA for 0d08dd8
1816. Truncate Sentence.py
@@ -0,0 +1,26 @@
1
+class Solution:
2
+ def truncateSentence(self, s: str, k: int) -> str:
3
+ last_space = -1
4
+ ans = []
5
+ number = 0
6
+ for i in range(len(s)):
7
+ if s[i] != " ":
8
+ continue
9
+
10
+ # When s[i] == ' '
11
+ number += 1
12
+ ans.append(s[last_space + 1 : i])
13
+ last_space = i
14
+ if number == k:
15
+ break
16
+ # Base case
17
+ if number < k:
18
+ ans.append(s[last_space + 1 :])
19
20
+ return " ".join(ans)
21
22
23
+s = "chopper is not a tanuki"
24
+k = 5
25
+obj = Solution()
26
+print(obj.truncateSentence(s, k))
0 commit comments