`

【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));
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics