您的位置:首页 > 编程语言 > Java开发

(java)Length of Last Word

2015-12-17 19:24 399 查看
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
.

思路:先判断这个字符串中包不包含有效字符,是不是全是空格,如果不是,则将这个字符串按照空格分隔,返还最好一个字符串的长度

代码如下(已通过leetcode)

public class Solution {

public int lengthOfLastWord(String s) {

boolean isempty=true;

for(int i=0;i<s.length();i++) {

if(s.charAt(i)!=' ') {

isempty=false;

break;

}

}

if(isempty) return 0;

String[] ss= s.split(" ");

return ss[ss.length-1].length();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: