每天一个小程序(七)--- Length Of Last Word

21 篇文章 0 订阅
14 篇文章 0 订阅

LengthOfLastWord

どこまで行っても私たちも、放課後のティータイム!

k-on!

前言:

昨天的鱼刺被我掏下去啦!今天去面试了个同学,感觉和之前的同学比较的话,他准备得不错。注意面试过程中有不会的就说不会,不要强答,越答越错,说不会面试官就直接跳过,之后对你的整体感觉会好很多,感觉就是全都会的样子。当然,不要什么都不会,嘿嘿嘿。。。


package string;

import java.util.Arrays;

/**
 * @author BlackSugar
 * @date 2019/4/17
 * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
 * <p>
 * If the last word does not exist, return 0.
 * <p>
 * Note: A word is defined as a character sequence consists of non-space characters only.
 * <p>
 * Example:
 * <p>
 * Input: "Hello World"
 * Output: 5
 */
public class LengthOfLastWord {
    /**
     * 获取字符串最后一个单词的长度
     * 思想:lastIndexOf、split
     *
     * @param s
     * @return
     */
    public int lengthOfLastWord(String s) {
        if (null == s || s.length() == 0) {
            return 0;
        }
        s = s.trim();
        int index = s.lastIndexOf(" "), length = s.length();
        return length - 1 - index;
    }

    public static void main(String[] args) {
        System.out.println(new LengthOfLastWord().lengthOfLastWord("a "));
    }
}

总结:

这道题简单得令人发指,没什么好说的,如果必须要说难点就是不能使用内置方法,必须用charAt,这样就要遍历一次,没什么意义,就没写了 ? 代码github

1、时间O(1)
2、空间O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值