LT_0003_最后一个单词的长度

一、题目描述

二、代码实现

2.1 字符串分割split()

将一个字符串用“ ”分割成多个字符串并存放在字符串数组中,然后求数组中最后一个字符串的长度即可。

package com.it.leetcode;

public class Day_0003 {
    public static void main(String[] args) {
        System.out.println(lengthOfLastWord("hello world")); //5
        System.out.println(lengthOfLastWord("hello world6")); //6
        System.out.println(lengthOfLastWord("hello world77")); //7
        System.out.println(lengthOfLastWord("hello world888")); //8
        System.out.println(lengthOfLastWord(" j")); //1
        System.out.println(lengthOfLastWord("   fly me   to   the moon  ")); //4
    }

    private static int lengthOfLastWord(String s) {
        String[] strArray = s.split(" ");
        String strNew = strArray[strArray.length - 1];
        return strNew.length();
    }
}

2.2 反向遍历字符串

package com.it.leetcode;

public class Day_0003 {
    public static void main(String[] args) {
        System.out.println(lengthOfLastWord1("hello world")); //5
        System.out.println(lengthOfLastWord1("hello world6")); //6
        System.out.println(lengthOfLastWord1("hello world77")); //7
        System.out.println(lengthOfLastWord1("hello world888")); //8
        System.out.println(lengthOfLastWord1(" j")); //1
        System.out.println(lengthOfLastWord1("   fly me   to   the moon  ")); //4
    }

    //反向遍历字符串
    private static int lengthOfLastWord1(String s) {
        int count = 0;//记录最后一个单词的个数
        int index = s.length() - 1;

        //先去除最后面的空格
        while (s.charAt(index) == ' ' && index >= 0) {
            index--;
        }
        //正式计算最后一个单词的长度。注意index >=0的条件一定要放在前面,避免出现访问下标为-1的情况
        while (index >= 0 && s.charAt(index) != ' ') {
            count ++;
            index --;
        }
        return count;
    }
}

三、运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值