Truncate Sentence

🏠 ⬅️ ➡️

A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).

  • For example, "Hello World ", "HELLO ", and "hello world hello world " are all sentences.

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 = "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 ".

Example 3:

Input: s = "chopper is not a tanuki ", k = 5 Output: "chopper is not a tanuki "

Constraints:

  • 1 <= s.length <= 500
  • k is in the range [1, the number of words in s].
  • s consist of only lowercase and uppercase English letters and spaces.
  • The words in s are separated by a single space.
  • There are no leading or trailing spaces.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program truncate_sentence
    implicit none

    character(len=500) :: s
    integer :: k
    character(len=500) :: result

    ! Examples
    s = "Hello how are you Contestant "
    k = 4
    write(*,*) 'Example 1:'
    call truncate_sentence_sub(s, k, result)
    write(*,'(A)') trim(result)

    s = "What is the solution to this problem "
    k = 4
    write(*,*) 'Example 2:'
    call truncate_sentence_sub(s, k, result)
    write(*,'(A)') trim(result)

    s = "chopper is not a tanuki "
    k = 5
    write(*,*) 'Example 3:'
    call truncate_sentence_sub(s, k, result)
    write(*,'(A)') trim(result)

contains

    subroutine truncate_sentence_sub(s, k, result)
        implicit none
        character(len=*), intent(in) :: s
        integer, intent(in) :: k
        character(len=*), intent(out) :: result

        integer :: i, j
        logical :: found_space

        result = ''
        do i = 1, len_trim(s)
            if (s(i:i) == ' ') then
                found_space = .true.
            else
                if (found_space) then
                    exit
                end if
            end if
        end do

        do j = 1, k-1
            do i = 1, len_trim(s)
                if (s(i:i) == ' ') then
                    exit
                end if
            end do
            result = trim(result) // s(j:i-1) // ' '
        end do

    end subroutine truncate_sentence_sub

end program truncate_sentence
Compiled
Executed
Correct
PROGRAM TRUNCATE_SENTENCE
      IMPLICIT NONE

      INTEGER, PARAMETER :: MAX_LEN = 500
      INTEGER, PARAMETER :: MAX_WORDS = 100

      CHARACTER(LEN=MAX_LEN) :: s
      INTEGER :: k
      INTEGER :: i, j
      CHARACTER(LEN=MAX_LEN) :: result

      READ(*,*) s
      READ(*,*) k

      ! Find the first k words in the sentence
      i = 1
      j = 1
      DO WHILE (i <= k .AND. j <= MAX_LEN)
        IF (s(j:j) == ' ') THEN
          i = i + 1
        END IF
        j = j + 1
      END DO

      ! Copy the first k words to the result string
      result = s(1:j-1)

      ! Print the result
      WRITE(*,*) TRIM(result)

      END PROGRAM TRUNCATE_SENTENCE
🌐 Data from online sources
def truncateSentence(s: str, k: int) -> str:
    words = s.split()
    return " ".join(words[:k])

The algorithm for all languages is the same: 1. First, we split the input string s by space character to get an array/list of words. 2. Then, we slice this array/list so that only the first k words are included. 3. Finally, we join the words back into a single string using space character, which is the final output string.

Using this common algorithm, we wrote functions for the respective programming languages. Note that in C++ and Java, we use a string stream and a string builder respectively for string manipulations as they are more efficient. On the other hand, in Python and JavaScript, slicing and joining strings are much easier to do with the built-in functions.

🌐 Data from online sources
#include <string>
#include <sstream>
using namespace std;

string truncateSentence(string s, int k) {
    istringstream is(s);
    string result, tmp;
    while (k--) {
        is >> tmp;
        result += tmp + " ";
    }
    result.pop_back();
    return result;
}

The algorithm for all languages is the same: 1. First, we split the input string s by space character to get an array/list of words. 2. Then, we slice this array/list so that only the first k words are included. 3. Finally, we join the words back into a single string using space character, which is the final output string.

Using this common algorithm, we wrote functions for the respective programming languages. Note that in C++ and Java, we use a string stream and a string builder respectively for string manipulations as they are more efficient. On the other hand, in Python and JavaScript, slicing and joining strings are much easier to do with the built-in functions.