LeetCode(48)-Length of Last Word

来源:互联网 发布:苹果7手机淘宝打不开 编辑:程序博客网 时间:2024/04/30 14:44

题目:

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