第9周 Length of Last Word
来源:互联网 发布:不用网络的麻将游戏 编辑:程序博客网 时间:2024/05/22 13:19
Length of Last Word
Leetcode algorithms problem 58: Length of Last Word
问题描述
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.问题提示
A word is defined as a character sequence consists of non-space characters only.
思路
1.一开始拿空字符来判断每个最后单词的长度,采取两个空格之间的长度作为输出,后面发现输入的字符串可以连续空字符,此法作罢
2.遍历字符串,如果不是空字符,temp变量++,否则变为0,当temp长度不为0时,将值赋给sum
代码
class Solution {public: int lengthOfLastWord(string s) { int sum=0; int temp=0; for(int i = 0; i < s.length(); i++){ if(s[i] != ' '){ temp++; }else{ temp = 0; } if(temp != 0){ sum = temp; } } return sum; }};};
时间复杂度: O(n)
空间复杂度: O(1)
阅读全文
0 0
- 第9周 Length of Last Word
- 第40题 Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- 0-1背包问题
- 我爱codewars
- css中清除浮动的标准方法
- mybatis级联查询
- javascript 类数组
- 第9周 Length of Last Word
- C/c++中计算函数运行时间的两种方法
- 一元多项式求导 (25)
- JavaScript 的怪癖 8:“类数组对象”
- MongoDb 命令查询所有数据库列表
- Ubuntu下google建图cartographer包移植
- ios-AddressBook框架
- EularProject 66:Diophantine equation
- Hadoop 2.5.2分布式集群配置(VirtualBox虚拟机模拟)