【leetcode】Length of Last Word
来源:互联网 发布:编程日志怎么写 编辑:程序博客网 时间:2024/06/15 05:27
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.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = “Hello World”,
return 5
思路:
从前向后扫描,扫描到空格,视为一个单词,用j记录单词的长度,但是需要注意“a b ”的情况,因此用wordlength来记录前一个单词的长度,来避免这种情况。
class Solution {public: int lengthOfLastWord(string s) { if(sizeof(s)==0) return 0; int i=0,j=0 int wordlength=0; while(s[i]!='\0') { if(s[i]!=' ') { i++; j++; wordlength=j; } else { j=0; i++; } } return max(wordlength,0); }};
网上看到的答案是从后面往前扫,这个会更快一些
class Solution {public: int lengthOfLastWord(const char *s) { int len=strlen(s); int sum=0; while(s[len-1]==' ') len--; for(int i=len-1;i>=0;i--) { if(s[i]!=' ') sum++; else break; } return sum; }};
0 0
- LeetCode: Length of Last Word
- LeetCode Length of Last Word
- LeetCode : Length of Last Word
- [Leetcode] Length of Last Word
- [LeetCode] Length of Last Word
- [LeetCode]Length of Last Word
- [leetcode]Length of Last Word
- Leetcode:Length of Last Word
- LeetCode-Length of Last Word
- [LeetCode] Length of Last Word
- [leetcode] Length of Last Word
- leetcode length of last word
- LeetCode - Length of Last Word
- leetcode:Length of Last Word
- LeetCode:Length of Last Word
- LeetCode | Length of Last Word
- LeetCode - Length of Last Word
- Leetcode: Length of Last Word
- 10 个免费的 HTML 视频转换工具
- Python 函数之seek
- linux 命令之 logger
- Spring声明式事务配置管理方法
- 5.5 杂记
- 【leetcode】Length of Last Word
- Java Exception Interview Questions
- Jetty 的工作原理以及与 Tomcat 的比较
- GetExitCodeThread
- 详细介绍windows下使用python pylot进行网站压力测试
- 程序员面试宝典里的一个小订正
- Java Collections Interview Questions
- redis缓存 脏数据
- STC 15F101单片机介绍