前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LintCode 最后一个单词的长度题目分析代码

LintCode 最后一个单词的长度题目分析代码

作者头像
desperate633
发布2018-08-22 11:27:51
2680
发布2018-08-22 11:27:51
举报
文章被收录于专栏:desperate633

题目

给定一个字符串, 包含大小写字母、空格' ' ,请返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 。

样例 给定 s = "Hello World",返回 5。

分析

两种方法,一个顺着找,一个倒着找。

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param s A string
     * @return the length of last word
     */
    public int lengthOfLastWord(String s) {
        // Write your code here
                int tLen = 0;  
        //int maxLen = 0;
        char[] sc = s.toCharArray();
        int lastLen = 0;  
        for (int i = 0; i < sc.length; i++)  
        {  
            if (sc[i] != ' ')  
            {  
                tLen++;  
                /*if (tLen > maxLen) 
                { 
                    maxLen = tLen; 
                }*/  
            } else  
            {  
                lastLen = tLen;  
                tLen = 0;  
            }  
        }  
        if (tLen != 0)  
        {  
            lastLen = tLen;  
        }  
        return lastLen;  
    }
}
代码语言:javascript
复制
public class Solution {
    /**
     * @param s A string
     * @return the length of last word
     */
    public int lengthOfLastWord(String s) {
        // Write your code here
                int tLen = 0;  
        //int maxLen = 0;
        int length = 0;
        char[] chars = s.toCharArray();
        for (int i = s.length() - 1; i >= 0; i--) {
            if (length == 0) {
                if (chars[i] == ' ') {
                    continue;
                } else {
                    length++;
                }
            } else {
                if (chars[i] == ' ') {
                    break;
                } else {
                    length++;
                }
            }
        }

        return length; 
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.12.18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档