leetcode------Length of Last Word

标题: Length of Last Word
通过率: 28.8%
难度: 简单

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.

本题看似简单实际动手操作起来还是比较难的,因为测试集是很不友好的,有以下几种需要考虑:

x:表示空格

1、“xaxxx”;

2、"xa"

3、"ax"

4、"xxxxxxxxx"

等等多种空格的组合,那么单纯的用找最后一个空格是不行的,本题刚开始做的时候我用了java的一个特性,就是trim()函数,将一个字符串的前后空格都去除了,这样做就只用考虑单词间的空格,然后就是用了一个lastindexof()函数查找最后一个空格的位置,如果在去除了前后空格后最后一个空格位置又为-1,那么说明就剩下一个单词了,返回trim()后的字符串长度即可。

利用java特性做的代码如下:

 1 public class Solution {
 2     public int lengthOfLastWord(String s) {
 3         int len=s.trim().length();
 4         s=s.trim();
 5         int tmp=s.lastIndexOf(" ");
 6         if(len==0) return 0;
 7          if(tmp<0)return len;
 8         return len-tmp-1;
 9     }
10 }

但是我感觉这样做出这个题目就没有意义了。如果不用任何函数做,那么应该从后向前找到第一个不为空的字母,然后继续向前找到第一个空格或者走到头,这之间的长度即为最后一个单词的长度,同时要记得处理空字符串,具体代码如下:

 1 public class Solution {
 2     public int lengthOfLastWord(String s) {
 3         int len=s.length();
 4         int sum=0;
 5         if(len-1<0)return 0;
 6         while(s.charAt(len-1)==' '){
 7             if(len-1<=0)return 0;
 8             len--;
 9         }
10         for(int i=len-1;i>=0;i--){
11             if(s.charAt(i)!=' '){
12                 sum+=1;
13             }
14             else
15             break;
16         }
17         return sum;
18     }
19 }
原文地址:https://www.cnblogs.com/pkuYang/p/4236286.html