Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
Example:
Input: "Hello World" Output: 5
最后一个单词的长度。弱智题,直接上代码了。记得要把input先trim一下,去掉前后多余的空格。
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var lengthOfLastWord = function (s) { 6 // corner case 7 if (s === null || s.length === 0) { 8 return 0; 9 } 10 11 // normal case 12 let input = s.trim(); 13 let count = 0; 14 for (let i = input.length - 1; i >= 0; i--) { 15 if (input[i] !== ' ') { 16 count++; 17 } else { 18 break; 19 } 20 } 21 return count; 22 };
Java实现
1 class Solution { 2 public int lengthOfLastWord(String s) { 3 // corner case 4 if (s == null || s.length() == 0) { 5 return 0; 6 } 7 8 // normal case 9 String input = s.trim(); 10 int count = 0; 11 for (int i = input.length() - 1; i >= 0; i--) { 12 if (input.charAt(i) != ' ') { 13 count++; 14 } 15 else { 16 break; 17 } 18 } 19 return count; 20 } 21 }