Leetcode 58: 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.

给定一个字符串, 包含大小写字母、空格 ' ',请返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

注意事项:一个单词的界定是,由字母组成,但不包含任何的空格。

案例:

输入: "Hello World"
输出: 5

分析:

该题较为简单,首先,字符串全部为空,那么不存在最后一个单词,即长度为0;其次只要将字符串按空格划分,取最后一个不为空的字串的长度即可。

 

 解法一:

class Solution {
  public int lengthOfLastWord(String s) {
    if (s.isEmpty()) return 0;

    String[] sStr = s.split(" ");
    for (int i=sStr.length-1; i>=0; i++){
      if (sStr[i] != "") return sStr[i].length();
    }
    return 0;
  }
}

posted @ 2018-04-15 16:28  小筝  阅读(101)  评论(0)    收藏  举报