您的位置:首页 > 其它

LeetCode(48)-Length of Last Word

2016-04-12 10:37 316 查看

题目:

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.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = "Hello World",
return 5.


思路:

题意:给定一个字符串,每个单词用“ ”隔开,求最后一个单词的长度,如果没有返回0

利用String.split(” “),分开成String数组,返回最后衣字符串的长度,考虑输入的字符串s为null,s= “ ”,s=“hello ”(以空格结尾)

-

代码:

public class Solution {
public int lengthOfLastWord(String s) {
if(s == null){
return 0;
}
String[] ss = s.split(" ");
int n = ss.length;
if(n < 1){
return 0;
}
String a = ss[n-1];
if(a == null){
return 0;
}
char[] aa = a.toCharArray();
return aa.length;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: