Length of Last Word
2015-06-26 16:31
567 查看
Length of Last Word
Total Accepted: 50713 TotalSubmissions: 180895My Submissions
Question
Solution
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.
Show Tags
Have you met this question in a real interview?
Yes
No
Discuss
思路:这一题曾经艾力跟我出过,当时我想的好简单然后好蠢,还打算从前往后进行计算。。后来虽然知道从后往前效率更高,但是没有考虑各种输入的情况,比如说字符串是“a“,” “等,今天又做了一遍,WA了n久,终于过了。。。
附上代码:
class Solution { public: int lengthOfLastWord(string s) { int len=s.length(); if(len==0) return 0; int num=0,j; for(int i=len-1;i>=0;i--) { num=0; if(isalpha(s[i])) { for(j=i;j>=0;j--) { if(s[j]!=' ') num++; if(s[j]==' ') break; } return num; } else continue; } } };
相关文章推荐
- java对cookie的操作
- 联机重做日志文件 (转)
- 从零开始--系统深入学习IOS(使用Swift---带链接)
- MyEclipse 8.6 安装Mylyn插件详细步骤
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/
- richedit插入图片错误
- xterm run command
- 渣渣ACM日记——540-奇怪的排序(NYOJ)
- 剖析一个java对象初始化顺序问题
- 当Fragment通过ViewPager嵌套Fragment时第二进入不显示的问题
- 正则表达式
- ssh学习路线
- 关于listview的一些属性
- Winform菜单之ContextMenuStrip
- Windows 10最新预览版10154曝光 接近99%的正式版
- postgresql 异步流复制
- js contains方法
- eclipse中 Perspective switch job 弹框问题
- apache 编译错误 configure: error: APR not found
- Unity Ray 射线检测