【leetcode】【58】Length of Last Word

来源:互联网 发布:广联达算量软件下载 编辑:程序博客网 时间:2024/06/06 03:26

一、问题描述

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.

二、问题分析

非常简单的一道题,只需要将原字符串trim一下,然后从后往前遍历即可,非空字符count++,碰到空字符return即可;也可以采用split方法,直接返回最后一个string的长度即可。

三、Java AC代码

public int lengthOfLastWord(String s) {        if(null == s||s.trim().length()==0){        return 0;        }        String tmp = s.trim();        int count = 0;        for(int i=tmp.length()-1;i>=0;i--){            if(tmp.charAt(i)!=' '){                count++;            }else{                return count;            }        }        return count;    }

public int lengthOfLastWord(String s) {        if(null == s||s.trim().equals("")){        return 0;        }        String[] splitString = s.trim().split(" ");        int len = splitString[splitString.length-1].length();return len;    }


0 0
原创粉丝点击