58. Length of Last Word

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

如果最后一个单词不存在,返回0.(自己理解有误,认为如"a  "这样即最后一个单词不存在,实际并不是,对该字符串来说,最后一个单词是a,长度为1)

注意:一个单词被定义为由不为空的字符组成的序列,即不包含' '.

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.

Example:

Input: "Hello World"
Output: 5

lvlolitte的解法
public int lengthOfLastWord(String s) {
    return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}

这里面主要用了trim()函数,trim()函数的作用为“去掉了字符串两端Unicode编码小于等于32(u0020)的所有字符”。链接的博客中详细解释了原因。

 我的解法

public int lengthOfLastWord(String s) {
  int count=0;
  int precount=0;
  for (char c : s.toCharArray()) {
    if(c==' ')
    count=0;
  else{
    count++;
    precount=count;
}

}
  return precount;
}



原文地址:https://www.cnblogs.com/mafang/p/8649323.html