LeetCode/solutions/58. Length of Last Word.md
2019-09-13 23:08:41 +08:00

19 lines
815 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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表示最后一个单词的结尾字母的indexlow表示最后一个单词的第一个字母的前一个index这样的话所求结果就是high - low。
# C++
``` 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;
}
};
```