[LeetCode] Truncate Sentence

Input: s = "Hello how are you Contestant", k = 4
Output: "Hello how are you"
Explanation:
The words in s are ["Hello", "how" "are", "you", "Contestant"].
The first 4 words are ["Hello", "how", "are", "you"].
Hence, you should return "Hello how are you".
Input: s = "What is the solution to this problem", k = 4
Output: "What is the solution"
Explanation:
The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].
The first 4 words are ["What", "is", "the", "solution"].
Hence, you should return "What is the solution".
Input: s = "chopper is not a tanuki", k = 5
Output: "chopper is not a tanuki"
class Solution(object):
def truncateSentence(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""

sentence = ""
acc = 0
for i in s.split(" "):
if acc < k:
sentence += i + " "
acc += 1
return sentence.rstrip(" ")

--

--

--

Learning, and posting my findings!

Love podcasts or audiobooks? Learn on the go with our new app.

Creating a Custom VPC with AWS CDK

Integrating Kubernetes with Jenkins, Github, and Docker

High Concurrency and Low Latency on Data Lakes with Lakehouse

Top 8 Places To Find Free Programming Courses

Migrating Content From One CMS to Another

5 ways learning programming is like learning a foreign language

A book to learn Spanish with the title “Fluent City”

Custom coding standard - why and how

Solving a Maze using A-star Algorithm

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matthew Boyd

Matthew Boyd

Learning, and posting my findings!

More from Medium

Search Insert Position (Solution For Leetcode Problem #35)

LeetCode 843. Guess the Word

MCLT — More Code Less Talk

The pandemic of Data Structures and Algorithms Courses

How to perform range addition in O(n) time and O(1) space complexity?