`

【LeetCode】- Length of Last Word(最后一个单词的长度)

 
阅读更多

[问题:]

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.

给你一个字符串,设法获取它最后一个单词的长度。如果这个单词不存在,则返回0。

[ 分析:]

A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World",
return 5.

[ 解法:]

public class Solution {

	public int lengthOfLastWord(String s) {
		if (s != null && !s.trim().equals("")) {
			String[] arr = s.trim().split(" ");
			int length = arr[arr.length - 1].length();
			return length;
		}
		return 0;
	}

	public static void main(String[] args) {
		String s = "leet code";
		System.out.println(new Solution().lengthOfLastWord(s));
	}
}


分享到:
评论

相关推荐

    c++-c++编程基础之leetcode题解第58题最后一个单词的长度.zip

    在本压缩包中,我们关注的是C++编程基础与LeetCode题目的结合,特别是针对第58题“最后一个单词的长度”(Length of Last Word)的解决方案。LeetCode是一个在线平台,提供各种算法题目,旨在提升程序员的编程技能和...

    机试高频考点.docx

    LeetCode上的题目如《将字符串转换为小写》(https://leetcode-cn.com/problems/to-lower-case/)和《求字符串最后一个单词的长度》(https://leetcode-cn.com/problems/length-of-last-word/)。 2. 异位词问题:考察...

    58. 最后一个单词的长度

    最后一个单词的长度](https://leetcode-cn.com/problems/length-of-last-word/)题目描述solution idea一次遍历参考文献 leetcode58:58. 最后一个单词的长度 题目描述 给定一个仅包含大小写字母和空格 ’ ’ 的字符...

    算法刷题笔记leetcode/lintcode

    - Length of Last Word(最后一个单词的长度) - Count and Say(猜数字序列) - **Integer Array**(整型数组操作) - Remove Element(移除元素) - Zero Sum Subarray(连续子数组的最大和) - Subarray Sum...

    Leetcode代码以及解答(2)

    - 给定一个字符串,返回最后一个单词的长度。 - **解决方案分析:** - **双指针:** - 从字符串末尾开始遍历,找到第一个非空格字符 `end`。 - 从 `end` 开始向前遍历,直到遇到空格或开头,找到 `start`。 - ...

Global site tag (gtag.js) - Google Analytics