LeetCode #58 length of Last Word
来源:互联网 发布:淘宝卖家恶意不发货 编辑:程序博客网 时间:2024/05/11 11:01
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.
<pre name="code" class="cpp">class Solution {public:int lengthOfLastWord(const char *s) {int cnt = 0;for(int i = 0; i < strlen(s); ++i){if(s[i] == ' ')continue;else{int j = i;while( j < strlen(s) && s[j] != ' ')//这里要提醒,j < strlen(s)条件必须放在前面,原因:在c++里前后都<span style="white-space:pre"></span><pre name="code" class="cpp" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 30px;"><span style="white-space:pre"></span>j++;<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"></span><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">//</span><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">可以,但是在Java中会报数组越界。是因为如果</span><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">j < strlen(s)放在后面</span>
cnt = j - i;<span style="white-space:pre"></span>//则先判断s[j] != ' '条件,此时j可能为strlen(s),所以报错。i = j;//C++中不报错是因为C++允许访问外面的地址空间,而java有自身的保护机制所以}<span style="white-space:pre"></span>//安全性更高,因此以后需注意有大小限制一定要放在最前面。}return cnt; }};
0 0
- [leetcode 58] Length of Last Word
- leetcode-58 Length of Last Word
- Leetcode NO.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, easy] Length of Last Word
- Length of Last Word (leetCode 58)
- leetcode[58]:Length of Last Word
- 【leetcode c++】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(c)
- leetcode 58: Length of Last Word
- leetCode #58 Length of Last Word
- MFC 串口编程总结
- oracle函数参数中=>的含义
- 获取request请求路径信息
- 统计单词出现的次数
- (算法设计技巧与分析)Majority
- LeetCode #58 length of Last Word
- linux fstab 使用指南
- hbase数据库错误总结 ——ERROR: Can't get master address from ZooKeeper; znode data == null
- ScrollView中图片的无限轮播(精简)
- iOS基础程序Demo
- 友坚三星4412开发板Linux平台下UT4412BV03裸机开发指南
- xxx定律 (1031)
- (算法设计技巧与分析)MinMax
- C#之NullReferenceException