<LeetCode OJ> 58. Length of Last Word
2017-06-18 17:34
537 查看
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 =
return
分析:
简单模拟思想。去掉尾部的空格并统计是字符的个数直到再次遇到空格就停止统计
或者用STL来写:
注:本博文为EbowTang原创。兴许可能继续更新本文。假设转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50498956
原作者博客:http://blog.csdn.net/ebowtang
' ',
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.
分析:
简单模拟思想。去掉尾部的空格并统计是字符的个数直到再次遇到空格就停止统计
class Solution { public: int lengthOfLastWord(string s) { int strLen=s.size(); int len=0; int i=0; while(s[strLen-i-1]==' ') i++; for(;i<strLen;i++) { if(s[strLen-i-1]>='A'&&s[strLen-i-1]<='Z' || s[strLen-i-1]>='a'&&s[strLen-i-1]<='z' ) len++; else break; } return len; } };
或者用STL来写:
class Solution { public: int lengthOfLastWord(string s) { int i = s.find_last_not_of(' '); return (i == string::npos) ? 0 : (i - s.find_last_of(' ', i)); } };
注:本博文为EbowTang原创。兴许可能继续更新本文。假设转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50498956
原作者博客:http://blog.csdn.net/ebowtang
相关文章推荐
- <LeetCode OJ> 58. Length of Last Word
- <LeetCode OJ> 168. Excel Sheet Column Title
- <LeetCode OJ>Single Number( I / II / III )【136 / 137 / 260】
- <LeetCode OJ>Reverse Bits【190】
- <LeetCode OJ>Implement Stack using Queues【225】
- <LeetCode OJ> 46. Permutations
- <LeetCode OJ> Min Stack【155】
- <LeetCode OJ> Nim Game【292】
- <LeetCode OJ> 55. Jump Game
- <LeetCode OJ> Invert Binary Tree【226】
- <LeetCode OJ> Same Tree【100】
- <LeetCode OJ> 62. Unique Paths
- <LeetCode OJ> Ugly Number / Ugly Number II【263 / 264】
- <LeetCode OJ> 28. Implement strStr()
- <LeetCode OJ> 152. Maximum Product Subarray
- <LeetCode OJ>Remove Element【27】
- <LeetCode OJ> 63. Unique Paths II
- <LeetCode OJ>Factorial Trailing Zeroes【172】
- <LeetCode OJ>Delete Node in a Linked List【237】
- <LeetCode OJ>Rotate Array【189】