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.

这一题很简单,但是有一个地方很无聊。 就是可能在一个word之后有很多空格,但是当你要得到last word length的时候 是要忽略这些空格的。 所以首先除去末尾的空格。

 1 public class Solution {
 2     public int lengthOfLastWord(String s) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(s == null || s.length() == 0) return 0;
 5         int i = 0;
 6         int tail = 0;
 7         for(;tail < s.length(); tail ++){
 8             if(s.charAt(s.length() - tail - 1) != ' ') break;
 9         }
10         while(i < s.length() - tail)
11         {
12             if(s.charAt(s.length() - tail - i - 1) == ' ') return i;
13             i ++;
14         }
15         return s.length() - tail;
16     }
17 }

第三遍:

 1 public class Solution {
 2     public int lengthOfLastWord(String s) {
 3         if(s == null || s.length() == 0) return 0;
 4         int right = s.length() - 1;
 5         while(right > -1 && s.charAt(right) == ' ') right --;
 6         int left = right;
 7         while(left > -1 && s.charAt(left) != ' ') left --;
 8         return right - left;
 9     } 
10 }

 

 

posted on 2013-10-04 06:46  Step-BY-Step  阅读(217)  评论(0编辑  收藏  举报

导航