Length of Last Word - easy problem and solution
In this exercise, we're going to find the length of a last word. For example :-
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
C# implementation (for simplicity and undestanability)
using System;
public class Solution {
public int LengthOfLastWord(string s) {
// Remove trailing spaces
s = s.TrimEnd();
// Find the last space
int lastSpace = s.LastIndexOf(' ');
// If there's no space, the whole string is one word
return s.Length - lastSpace - 1;
}
}
class Program {
static void Main(string[] args) {
Solution sol = new Solution();
Console.WriteLine(sol.LengthOfLastWord("Hello World")); // Output: 5
Console.WriteLine(sol.LengthOfLastWord(" fly me to the moon ")); // Output: 4
Console.WriteLine(sol.LengthOfLastWord("luffy is still joyboy")); // Output: 6
Console.WriteLine(sol.LengthOfLastWord("singleword")); // Output: 10
}
}
Or in Golang
package main
import (
"fmt"
"strings"
)
func lengthOfLastWord(s string) int {
// Remove trailing spaces
s = strings.TrimRight(s, " ")
// Find the last space
lastSpace := strings.LastIndex(s, " ")
// If no space found, the whole string is one word
return len(s) - lastSpace - 1
}
func main() {
fmt.Println(lengthOfLastWord("Hello World")) // Output: 5
fmt.Println(lengthOfLastWord(" fly me to the moon ")) // Output: 4
fmt.Println(lengthOfLastWord("luffy is still joyboy")) // Output: 6
fmt.Println(lengthOfLastWord("singleword")) // Output: 10
}
Comments