mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 58. Length of Last Word.md
This commit is contained in:
parent
a7e07509b8
commit
1e2bddceec
18
58. Length of Last Word.md
Normal file
18
58. Length of Last Word.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
# [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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user