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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5

 

题意:

最后一个词的长度

 

Solution1: Just like do the simulation of  s.trim()

 

code

 1 /*
 2 Time: O(n). 
 3 Space: O(1). 
 4 */
 5 class Solution {
 6      public int lengthOfLastWord(String s) {
 7         // corner case
 8         if (s == null || s.length() == 0) return 0;
 9         int right = s.length() - 1;
10         int i = 0;
11         // 先把last word右边的空格扫清
12         while (right > 0 && s.charAt(right) == ' ') right--;
13         i = right;
14         // 定住right, 用i来扫出last word的长度
15         while (i >= 0 && s.charAt(i) != ' ') i--;
16         return right - i;
17     }    
18 }

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄