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.

思路:字符串由前后空格分隔

java:

  1. public int lengthOfLastWord(String s) {
  2. int slen = s.length();
  3. int index = slen-1;
  4. while(index>=0 && s.charAt(index)==' ') index--;
  5. if(index<0) return 0;
  6. int end = index+1;
  7. while(index>=0 && s.charAt(index)!=' ') index--;
  8. int start = index+1;
  9. return end - start;
  10. }
posted @ 2014-07-27 12:32  purejade  阅读(80)  评论(0)    收藏  举报