mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
19 lines
811 B
Markdown
19 lines
811 B
Markdown
![]() |
# [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word/description/)
|
|||
|
# 思路
|
|||
|
求字符串所表示的单词中最后一个单词的字母数。
|
|||
|
用high表示字符串中从右开始第一个非空格字符所在index或者high==-1表示没有字母,low表示high从左边起第一个空格的index或者low==-1表示high左边没有空格了。
|
|||
|
即high表示最后一个单词的结尾字母的index,low表示最后一个单词的第一个字母的前一个index,这样的话,所求结果就是high - low。
|
|||
|
# C++
|
|||
|
```
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
int lengthOfLastWord(string s) {
|
|||
|
int high = s.size() - 1, low;
|
|||
|
while(high >= 0 && s[high] == ' ') high--;
|
|||
|
low = high;
|
|||
|
while(low >= 0 && s[low] != ' ') low--;
|
|||
|
return high - low;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|