From 1e2bddceeca860d52cd18a3ff17d5f83b677966d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Sun, 7 Oct 2018 23:54:09 +0800 Subject: [PATCH] Create 58. Length of Last Word.md --- 58. Length of Last Word.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 58. Length of Last Word.md diff --git a/58. Length of Last Word.md b/58. Length of Last Word.md new file mode 100644 index 0000000..c6445f3 --- /dev/null +++ b/58. Length of Last Word.md @@ -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; + } +}; +```