58. Length of Last Word
給定一個由單詞和空格組成的字符串 s,返回字符串中最後一個單詞的長度。
一個單詞是由非空格字符組成的最大的子字符串。
範例 1:
輸入:s = "Hello World" 輸出:5 解釋:最後一個單詞是 "World",其長度為 5。
Python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
# Trim any trailing spaces
s = s.rstrip()
# Split the string into words using spaces
words = s.split(" ")
# Return the length of the last word
return len(words[-1])
16.54MB, 29ms
C++
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
int length = 0;
int n = s.size();
// Skip trailing spaces
int i = n - 1;
while (i >= 0 && s[i] == ' ') {
i--;
}
// Count the length of the last word
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
};
7.77MB, 0ms
Javascript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
// Trim any trailing spaces
s = s.trim();
// Split the string into words using spaces
const words = s.split(' ');
// Return the length of the last word
return words[words.length - 1].length;
};
48.82MB, 46ms