题目:难度(Easy)

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example, 
Given s = "Hello World",
return 5.
TagsString

分析:最后一个单词的理解:最后一个单词的后面和前面均允许有空白符;如果串中只有一个单词也是最后一个单词;全是空白符就一个单词也没有,也就没有最后一个单词之说了。

思路:开始打算用for程序遍历整个string,然后找到所有的空格键,在找到空格键之间的word,后来发现情况太复杂,主要是空格键若在string的首和尾,会有各种可能,借鉴别人的方法,用strip()函数除去首位的空格键,再从后往前找到所有在中间的空格键

str.strip()---除去左右的空格键,

str.lstrip()---除去左边的空格键

str.rstrip()---除去右边的空格键

Leetcode58-Length of Last Word

相关文章:

  • 2022-12-23
  • 2021-12-24
  • 2021-05-20
  • 2021-07-11
猜你喜欢
  • 2022-01-11
相关资源
相似解决方案