Leetcode#58. Length of Last Word
来源:互联网 发布:淘宝宝贝宣言词怎么写 编辑:程序博客网 时间:2024/05/20 14:17
题目
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.
题意
给一个字符串分隔符为空格,求出字符串中最后一个单词的长度输出。
思路
从后向前找。
C++语言
class Solution {public: int lengthOfLastWord(string s) { int start = s.size()-1,res = 0; for(int i = s.size()-1; i>=0; i--) { if(s[i] != ' ') { start = i; break; } } for(int i = start; i>=0; i--) { if(s[i]!=' ') res++; else break; } return res; }};
Python语言
注意range(n,m,d)代表从n 到m-1,每次增加d个。
class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ res = 0 start =len(s)-1 for index in range(len(s)-1,-1,-1): if s[index]!=" ": start = index break for index in range(start,-1,-1): if s[index]!=" ": res = res + 1 else: break return res
阅读全文
0 0
- 58. Length of Last Word Leetcode Python
- [LeetCode]58.Length of Last Word
- LeetCode --- 58. Length of Last Word
- [Leetcode] 58. Length of Last Word
- [leetcode] 58.Length of Last Word
- LeetCode - 58. Length of Last Word
- <LeetCode OJ> 58. Length of Last Word
- 58. Length of Last Word LeetCode
- 【LeetCode】58. Length of Last Word
- leetcode 58. Length of Last Word
- LeetCode *** 58. Length of Last Word
- LeetCode 58. Length of Last Word
- leetcode-58. Length of Last Word
- LeetCode-58.Length of Last Word
- [leetcode] 58. Length of Last Word
- LeetCode 58. Length of Last Word
- Leetcode-58. Length of Last Word
- leetcode-java-58. Length of Last Word
- Jenkins基础入门-2-把Jenkins服务部署在Tomcat下
- 计算机网络体系结构
- 第二周java作业
- 递归和分治策略之二分搜索法
- How can I plot an image (.jpg) in MATLAB in both 2-D and 3-D?
- Leetcode#58. Length of Last Word
- AFNetworking不支持text/plain,错误解决方法"Request failed: unacceptable content-type: text
- 引爆头条视频几百上千粉,月流水十几万玩法
- GCC简介
- 欢迎使用CSDN-markdown编辑器
- HttpClient Examples
- sql数据库中的TIMESTAMP属性
- Android Sqlite 数据库升级
- 在MFC程序中使用控制台输出打印信息(VS2010)