Posts

Showing posts from April, 2021

Truncate Sentence LeetCode Solution - The Coding Shala

Home >> LeetCode >> Truncate Sentence  In this post, we will learn how to solve LeetCode's Truncate Sentence problem and will implement its solution in Java. Truncate Sentence Problem You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it. Example 1: 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". Example 2: Input: s = "chopper is not a tanuki", k = 5 Output: "chopper is not a tanuki" Practice this problem on LeetCode . LeetCode - Truncate Sentence Java Solution Approach 1 First, convert the given string to