leetcode-058-最后一个单词的长度

文章提供了两种Java方法来找出给定字符串中最后一个单词的长度。第一种是顺序遍历,第二种是反向遍历。两种方法都考虑了字符串中至少存在一个单词的情况,并通过判断空格来确定单词边界。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目及测试

package pid058;
/* 58. 最后一个单词的长度
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。

单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。

 

示例 1:

输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。
示例 2:

输入:s = "   fly me   to   the moon  "
输出:4
解释:最后一个单词是“moon”,长度为4。
示例 3:

输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。
 

提示:

1 <= s.length <= 104
s 仅有英文字母和空格 ' ' 组成
s 中至少存在一个单词
*/


public class main {
	
	public static void main(String[] args) {
		String [] testTable = {"luffy is still joyboy","   fly me   to   the moon  "};
		for (String ito : testTable) {
			test(ito);
		}
	}
		 
	private static void test(String ito) {
		Solution solution = new Solution();
		int rtn;
		long begin = System.currentTimeMillis();
		System.out.print(ito);		    
		System.out.println();
		//开始时打印数组
		
		rtn= solution.lengthOfLastWord(ito);//执行程序
		long end = System.currentTimeMillis();	
		
		System.out.println("rtn=" );
		System.out.print(rtn);
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

解法1(成功,1ms,较慢)

顺序遍历字符串

package pid058;

class Solution {
    public int lengthOfLastWord(String s) {
    	int length = s.length();
    	if(length == 0){
    		return 0;
    	}
    	int result = 0;
    	int max = 0;
    	for(int i=0;i<length;i++){
    		if(s.charAt(i)==' '){
    			if(max != 0){
    				result = max;
        			max = 0;
    			}
    		}else{
    			max++;
    		}
    	}
    	if(max != 0){
    		result = max;
    	}
    	return result;
    }
}

解法2(别人的)

反向遍历
题目要求得到字符串中最后一个单词的长度,可以反向遍历字符串,寻找最后一个单词并计算其长度。

由于字符串中至少存在一个单词,因此字符串中一定有字母。首先找到字符串中的最后一个字母,该字母即为最后一个单词的最后一个字母。

从最后一个字母开始继续反向遍历字符串,直到遇到空格或者到达字符串的起始位置。遍历到的每个字母都是最后一个单词中的字母,因此遍历到的字母数量即为最后一个单词的长度。

class Solution {
    public int lengthOfLastWord(String s) {
        int index = s.length() - 1;
        while (s.charAt(index) == ' ') {
            index--;
        }
        int wordLength = 0;
        while (index >= 0 && s.charAt(index) != ' ') {
            wordLength++;
            index--;
        }
        return wordLength;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值