首页 > 其他 > 详细

LeetCode: 58. Length of Last Word

时间:2016-08-10 20:52:06      阅读:177      评论:0      收藏:0      [点我收藏+]

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。

 

思路1:

从后往前找到第一个不为空格的字符,记录其位置,从当前位置往前找到第一个空格的位置或者直到开头。

注意:边界检测,循环的时候要保证当前位置>=0

 

public class Solution 
{
    public int lengthOfLastWord(String s) 
    {
        if (s == null || s.length() == 0)
        {
            return 0;
        }
        
        int start = 0;
        int end = s.length()-1;
        
        while (end >= 0 && s.charAt(end) == ‘ ‘)
        {
            end--;
        }
        start = end;
        
        while (end >= 0 && s.charAt(end) != ‘ ‘)
        {
            end--;
        }
        
        if (start < 0)
        {
            return 0;
        }
        
        return start-end;
    }
}

 

思路2:

用split函数直接把字符串按照空格分隔,注意split(" +")可以分隔多个连续空格,如果返回数组长度为0,说明没有单词返回0,否则返回分隔后数组的最后一个element的长度。

public class Solution 
{
    public int lengthOfLastWord(String s) 
    {
        if (s == null || s.length() == 0)
        {
            return 0;
        }
        
        String[] temp = s.split(" +");
        
        return temp.length == 0 ? 0 : temp[temp.length-1].length();
    }
}

 

LeetCode: 58. Length of Last Word

原文:http://www.cnblogs.com/snakech/p/5758085.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!