赞
踩
先将字符串转换成字符数组
由于我们需要获取最后一个单词的长度,所以我们从后往前遍历字符数组
我们还需判断所遍历的字符是不是字母,即判断每个字符对应的ASCII值即可,用计数器count来储存单词长度
当遍历到第一个字母时,将flag的值从flase置为true,之后的循环中,若遍历到字母,则count++,若遍历到的字符不是字母,则直接结束循环,返回count
- char[] cs = s.toCharArray();
- int i = cs.length - 1;
- int count = 0;
- boolean flag = false;
- while (i>=0) {
- if ((cs[i] >= 65 && cs[i] <= 90) || (cs[i] >= 97 && cs[i] <= 122)) {
- count++;
- flag = true;
- }else{
- if(flag){
- break;
- }
- }
- i--;
- }
- return count;

官方题解采用的也是反向遍历的操作,和我的思路是一样的,只是代码稍有不同
- 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;
- }
- }
-
- 作者:力扣官方题解
- 链接:https://leetcode.cn/problems/length-of-last-word/
- 来源:力扣(LeetCode)
- 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。