leetcode 58:Length of Last Word

来源:互联网 发布:2017淘宝客服奖惩制度 编辑:程序博客网 时间:2024/04/28 02:11

题目:
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);    }}
0 0
原创粉丝点击