[leetcode]58. Length of Last Word最后一个词的长度

it2025-12-05  14

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

 

题意:

最后一个词的长度

 

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 }

 

转载于:https://www.cnblogs.com/liuliu5151/p/10731176.html

最新回复(0)