LeetCode OJ: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.

求最后一个非空单词的长度而已,没什么注意点,直接看代码,理解题目意思就可以了:

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         int len  = s.length();
 5         if(len == 0) return 0;
 6         while(s[len - 1] == ' ')
 7             if(len - 1 >= 0)
 8                 len--;
 9             else
10                 return 0;
11         len--;
12         int lenCount = 0;
13         while(s[len] != ' ' && len >= 0){
14             lenCount++, len--;
15         }
16         return lenCount;
17     }
18 };

 java版本的代码如下所示,倒过来读很容易了:

 1 public class Solution {
 2     public int lengthOfLastWord(String s) {
 3         int i = s.length() - 1;
 4         while(i >= 0 && s.charAt(i) == ' ')
 5             i--;
 6         int end = i+1;
 7         while(i >= 0 && s.charAt(i) != ' ')
 8             i--;
 9         int start = i+1;
10         return end - start;
11     }
12 }

 

posted @ 2015-10-22 10:13  eversliver  阅读(265)  评论(0编辑  收藏  举报