点击查看答案
方法一:可以直接从后往前求解。
方法二:把字符串 `s` 倒序,求第一个单词的长度。
本题采用方法二。在做完方法二后,建议用方法一实现一下。
## 复杂度
- 时间复杂度: `O(N)`.
- 空间复杂度: `1`.
## Python
```python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s = s[::-1] # Reverse the string
start_index = 0
while start_index < len(s) and s[start_index] == ' ':
start_index += 1
end_index = start_index
while end_index < len(s) and s[end_index] != ' ':
end_index += 1
return end_index - start_index
```
## Ruby
```ruby
# @param {String} s
# @return {Integer}
def length_of_last_word(s)
s.reverse!
start_index = 0
while s[start_index] == ' '
start_index += 1
end
end_index = start_index
while end_index < s.size && s[end_index] != ' '
end_index += 1
end
end_index - start_index
end
```
## Java
```java
class Solution {
public int lengthOfLastWord(String s) {
// Reverse the string
var sb = new StringBuilder(s);
String reversed = sb.reverse().toString();
var startIndex = 0;
// Skip leading spaces (which were trailing spaces in original)
while (startIndex < reversed.length() && reversed.charAt(startIndex) == ' ') {
startIndex++;
}
var endIndex = startIndex;
while (endIndex < reversed.length() && reversed.charAt(endIndex) != ' ') {
endIndex++;
}
return endIndex - startIndex;
}
}
```
## Other languages
```java
// Welcome to create a PR to complete the code of this language, thanks!
```
亲爱的力扣人,为了您更好的刷题体验,请访问 [LeetCode.to](https://leetcode.to/zh)。
本站敢称力扣题解最佳实践,终将省你大量刷题时间!
原文链接:[58. 最后一个单词的长度 - LeetCode Python/Java/C++/JS/C#/Go/Ruby 题解](https://leetcode.to/zh/leetcode/58-length-of-last-word).
GitHub 仓库: [leetcode-python-java](https://github.com/leetcode-python-java/leetcode-python-java).