LeetCode 58 Length of Last Word题解

来源:互联网 发布:origin mac版 编辑:程序博客网 时间:2024/06/06 03:37

题目地址:https://leetcode.com/problems/length-of-last-word/

题目:

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.

如果不存在,返回0。

Note: A word is defined as a character sequence consists of non-space characters only.

For example, 
Given s = "Hello World",
return 5.

算法思想:

采用顺序遍历字符串的每一个字符的方式,用一个int型变量len记录当前匹配到的非‘ ’字符长度,每次匹配到空,len归0,否则,len++。

Java代码实现:

public class Solution {    public int lengthOfLastWord(String str) {        if(str==null||str.length()==0)        {            return 0;        }else        {            int len=0;            for(int i=0;i<str.length();i++)            {                if(str.charAt(i)!=' ')                {                    len++;                }else                {                    len=0;                }            }            return len;        }    }}


0 0
原创粉丝点击