58. Length of Last Word #49
-
Given a string A word is a maximal substring1 consisting of non-space characters only. Example 1:
Example 2:
Example 3:
Constraints:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 58. Length of Last Word <?php
function lengthOfLastWord($s) {
// Trim the string to remove any leading or trailing spaces
$trimmed = trim($s);
// Split the string by spaces
$words = explode(' ', $trimmed);
// Get the last word from the array
$lastWord = end($words);
// Return the length of the last word
return strlen($lastWord);
}
// Example usage:
$s1 = "Hello World";
$s2 = " fly me to the moon ";
$s3 = "luffy is still joyboy";
echo lengthOfLastWord($s1); // Output: 5
echo lengthOfLastWord($s2); // Output: 4
echo lengthOfLastWord($s3); // Output: 6
?> Explanation:
Example Walkthrough:
This code handles the given constraints and ensures that we correctly find the length of the last word in any valid input string. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 58. Length of Last Word