Algorithm
Problem Name: 58. Length of Last Word
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 (A substring is a contiguous non-empty sequence of characters within a string.) 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' '
.- There will be at least one word in
s
.
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
#include <string.h>
int lengthOfLastWord(char* s) {
if (s == NULL) return 0;
int len = strlen(s);
if (len == 0) return 0;
int count = 0;
int i;
for (i = len - 1; i >= 0; i--) {
if (s[i] == ' ') {
if (count == 0) continue;
else break;
}
count++;
}
return count;
}
int main() {
char s[] = "Hello World ";
/* should be 5 */
printf("%d\n", lengthOfLastWord(s));
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int lengthOfLastWord(string s) {
int i = s.size() - 1;
while(i >= 0 && s[i] == ' ') i--;
int j = i;
while(j >= 0 && s[j] != ' ') j--;
return i - j;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int lengthOfLastWord(String s) {
int idx = s.length() - 1;
while (idx >= 0 && s.charAt(idx) == ' ') {
idx--;
}
int currIdx = idx;
while (idx >= 0 && s.charAt(idx) != ' ') {
idx--;
}
return currIdx - idx;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Javascript Programming
Code -
Javascript Programming
const lengthOfLastWord = function(s) {
const arr = s.split(" ");
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i].length > 0) return arr[i].length;
}
return 0;
};
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if len(s)==0:
return 0
count=0
prev_count=0
for letter in s:
if count>0:
prev_count=count
if letter==" ":
count=0
continue
count+=1
if count>0:
return count
else:
return prev_count
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _058_LengthOfLastWord
{
public int LengthOfLastWord(string s)
{
var index = s.Length - 1;
while (index >= 0 && s[index] == ' ')
{
index--;
}
var result = 0;
while (index >= 0 && s[index] != ' ')
{
result++;
index--;
}
return result;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output