您的位置:首页 > 其它

leetcode 58:Length of Last Word

2015-07-09 01:09 501 查看
题目:

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.

分析:

本题考查字符串的操作,一个字符串中可能包含多个单词,单词之间有空格,要求返回字符串中最后一个单词的长度。可以用空格为分隔符划分字符串,将单词存入数组中,得到最后一个单词的长度。分割字符串在数据操作中是必要的一步。

代码:

public class lenOfLastWord {
public static int lengthOfLastWord(String s){
String wordList[]=s.split(" ");
int len=wordList.length;
if(len>0){
char[] lastWord=wordList[len-1].toCharArray();
return lastWord.length;
}else{
return 0;
}
}
public static void main(String[] args){
String a=" ";
int result=lengthOfLastWord(a);
System.out.println("lastWord:"+result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: