LeetCode 58 Length of Last Word

来源:互联网 发布:网络直播一群无聊人 编辑:程序博客网 时间:2024/05/21 22:38

原题:(频率1)

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.




题意:最后一个词的长度





代码和思路

class Solution {    public int lengthOfLastWord(String s) {        //去掉首尾空格        s = s.trim();        if(s.length()==0 || s==null){            return 0;        }        char [] c = s.toCharArray();        int index = 0;        int end = c.length;        for(int i=0;i<c.length;i++){            if(c[i]==' '){                //最后一个字符串的开头                index = i+1;            }        }        return end - index;    }}



原创粉丝点击