LeetCode 1816: Truncate Sentence Solution

Master LeetCode problem 1816 (Truncate Sentence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1816. Truncate Sentence

Problem Explanation

Explanation:

To solve this problem, we can split the input sentence s into words using the space character as the delimiter. Then we can take the first k words and concatenate them back together with a space between each word to form the truncated sentence.

Algorithm:

  1. Split the input sentence s into individual words using the space character as the delimiter.
  2. Take the first k words from the list of words.
  3. Join these k words back together with a space between each word to form the truncated sentence.
  4. Return the truncated sentence.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input sentence s.

Space Complexity:

The space complexity of this algorithm is O(n), where n is the length of the input sentence s.

:

Solution Code

class Solution {
    public String truncateSentence(String s, int k) {
        String[] words = s.split(" ");
        StringBuilder truncated = new StringBuilder();
        for (int i = 0; i < k; i++) {
            truncated.append(words[i]);
            if (i < k - 1) {
                truncated.append(" ");
            }
        }
        return truncated.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1816 (Truncate Sentence)?

This page provides optimized solutions for LeetCode problem 1816 (Truncate Sentence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1816 (Truncate Sentence)?

The time complexity for LeetCode 1816 (Truncate Sentence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1816 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1816 in Java, C++, or Python.

Back to LeetCode Solutions