(java)Length of Last Word

来源:互联网 发布:linux shell exec 编辑:程序博客网 时间:2024/06/06 04:25

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

0 0
原创粉丝点击