LeetCode:最后一个单词的长度

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

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

示例 1:

输入:s = "Hello World"
输出:5
示例 2:

输入:s = "   fly me   to   the moon  "
输出:4
示例 3:

输入:s = "luffy is still joyboy"
输出:6

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/length-of-last-word
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package com.wei.happydemo;

public class Solution {
    public static 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;
    }

    public static void main(String[] args) {
        String str="ad dff dfga q ";
        int i = lengthOfLastWord(str);
        System.out.println(i);
    }
}

class Solution {
    public int lengthOfLastWord(String s) {

//首先要清楚的是最后一个是空格还是字母
//如果不是字母 就从后往前进行判断 直到遇见字母停下
int index = s.length() - 1;
while(s.charAt(index) == ' '){
    index--;
}
//到这里就是遇到了字母
//然后进行判断,如果是遇到了下一个空格且索引大于等于0 就说明要么是最后一个字母,要么是只有一个字母
int wordLength = 0;
while(index >= 0 && s.charAt(index) != ' '){
    wordLength++;
    index--;
}
return wordLength;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳光不锈@

如果有帮助的话,打赏一下吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值