描述

给你一个字符串 s,由若干单词组成,单词之间用空格隔开。返回字符串中最后一个单词的长度。如果不存在最后一个单词,请返回 0 。单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。

Tag

string

思路

  • 从后往前遍历字符串,过滤空格。然后再从后向前遍历直到为空或遇到空格为止。
  • 所以完整过程为先从后过滤掉空格找到单词尾部,再从尾部向前遍历,找到单词头部,最后两者相减,即为单词的长度
  • 时间复杂度:O(n),n为结尾空格和结尾单词总体长度

代码

方法一

  1. class Solution {
  2. public int lengthOfLastWord(String s) {
  3. int end = s.length()-1;
  4. while(end >= 0 && s.charAt(end) ==' '){
  5. end--;
  6. }
  7. if(end < 0){
  8. return 0;
  9. }
  10. int start = end;
  11. while(start >= 0 && s.charAt(start) != ' '){
  12. start--;
  13. }
  14. return end - start;
  15. }
  16. }

方法二

神仙代码

  • 去掉空格
  • 定位字符串中最后一个空格的的位置
    1. class Solution {
    2. public int lengthOfLastWord(String s) {
    3. if(s == null || s.length() == 0)
    4. {
    5. return 0;
    6. }
    7. return s.trim().length() - 1 - s.trim().lastIndexOf(" ");
    8. }
    9. }