首页 > 试题广场 >

字符串最后一个单词的长度

[编程题]字符串最后一个单词的长度
  • 热度指数:14039 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给出一个只包含大小写字母和空格的字符串s,请返回字符串中最后一个单词的长度
如果字符串中没有最后一个单词,则返回0
注意:单词的定义是仅由非空格字符组成的字符序列。
例如:
s ="Hello World",
返回5。
解法一:

class Solution {
    public int lengthOfLastWord(String s) {
       String[] array = s.trim().split("\\s+");
        return array[array.length - 1].length();
    }
}


解法二:
public int lengthOfLastWord(String s) {
        if (s == null | s.isEmpty()) return 0;

      
        int begin = 0, end = s.length();
        while (end > 0 && s.charAt(end - 1) == ' ') {
            end--;
        }
      
        for (int i = 0; i < end; i++) {
            if (s.charAt(i) == ' ') {
                begin = i + 1;
            }
        }

        return end - begin;
    }

解法三:

public int lengthOfLastWord(String s) {

        int count = 0;
        for (int i = s.length() - 1; i >= 0; i--) {

            if (s.charAt(i) == ' ') {
                if (count > 0) {
                    break;
                }
            } else {
                count++;
            }
        }
        return count;
    }



编辑于 2018-12-16 15:43:14 回复(0)
return s.trim().length()-s.trim().lastIndexOf(" ")-1;

weilenvren

发表于 2018-09-09 20:46:21 回复(0)

Java Solution

将字符串按空格分割,返回最后一个单词长度即可。

public class Solution {
    public int lengthOfLastWord(String s) {
        String[] res = s.split(" ");
        if (res.length > 0)
            return res[res.length - 1].length();
        return 0;
    }
}
发表于 2018-07-04 10:27:09 回复(0)

public class Solution {
    public int lengthOfLastWord(String s) {
        if(s.length()==0)return 0;
        String[] sArray=s.trim().split(" ");
        return sArray[sArray.length-1]!=null?sArray[sArray.length-1].length():0;
    }
}

发表于 2018-01-22 18:48:27 回复(0)
public int lengthOfLastWord(String s) {
    
    return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}
}

发表于 2017-03-12 12:33:09 回复(0)
public class Solution {
    public int lengthOfLastWord(String s) {
		String[] split = s.split("\\s+");
		if(split.length == 0) return 0;
		return split[split.length - 1].length();
	}
}

发表于 2016-11-06 15:59:40 回复(0)

问题信息

难度:
6条回答 15637浏览

热门推荐

通过挑战的用户

查看代码