Given a string s
consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World " Output: 5 Explanation: The last word is "World " with length 5.
Example 2:
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon " with length 4.
Example 3:
Input: s = "luffy is still joyboy " Output: 6 Explanation: The last word is "joyboy " with length 6.
Constraints:
1 <= s.length <= 104
s
consists of only English letters and spaces ' '
.s
.program main
implicit none
character(len=100) :: s
integer :: n
call get_command_argument(1, s)
n = len_trim(s)
write (*,*) 'n = ', n
end program main
n = 0
module last_word_length
implicit none
contains
function last_word_length_fcn(s) result(length)
character(len=*), intent(in) :: s
integer :: length
! Declare variables
integer :: i, j
! Initialize variables
length = 0
i = len(s)
! Find the last word
do while (i > 0)
if (s(i:i) == ' ') then
i = i - 1
else
exit
end if
end do
! Calculate the length of the last word
j = i
do while (j > 0)
if (s(j:j) /= ' ') then
length = length + 1
end if
j = j - 1
end do
end function last_word_length_fcn
end module last_word_length
program main
use last_word_length
implicit none
! Declare variables
character(len=100) :: s
integer :: length
! Test case 1
s = "Hello World "
length = last_word_length_fcn(s)
write (*,*) "Test case 1: ", length
! Test case 2
s = " fly me to the moon "
length = last_word_length_fcn(s)
write (*,*) "Test case 2: ", length
! Test case 3
s = "luffy is still joyboy "
length = last_word_length_fcn(s)
write (*,*) "Test case 3: ", length
end program main
Test case 1: 10 Test case 2: 14 Test case 3: 18
def length_of_last_word(s: str) -> int:
length = 0
tail = len(s) - 1
while tail >= 0 and s[tail] == ' ':
tail -= 1
while tail >= 0 and s[tail] != ' ':
length += 1
tail -= 1
return length
The algorithm for finding the length of the last word in a string containing multiple words separated by spaces is as follows:
This algorithm is implemented in each of the given programming languages (C++, Java, Python, and JavaScript) with the appropriate syntax and variable initialization. The functions are named lengthOfLastWord
for C++, Java, and JavaScript, and length_of_last_word
for Python.
int lengthOfLastWord(string s) {
int length = 0;
int tail = s.length() - 1;
while (tail >= 0 && s[tail] == ' ') tail--;
while (tail >= 0 && s[tail] != ' ') {
length++;
tail--;
}
return length;
}
The algorithm for finding the length of the last word in a string containing multiple words separated by spaces is as follows:
This algorithm is implemented in each of the given programming languages (C++, Java, Python, and JavaScript) with the appropriate syntax and variable initialization. The functions are named lengthOfLastWord
for C++, Java, and JavaScript, and length_of_last_word
for Python.