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
原创粉丝点击