当前位置:   article > 正文

LeetCode力扣每日一题(Java):58、最后一个单词的长度_力扣第58题

力扣第58题

一、题目

二、解题思路

1、我的思路

先将字符串转换成字符数组

由于我们需要获取最后一个单词的长度,所以我们从后往前遍历字符数组

我们还需判断所遍历的字符是不是字母,即判断每个字符对应的ASCII值即可,用计数器count来储存单词长度

当遍历到第一个字母时,将flag的值从flase置为true,之后的循环中,若遍历到字母,则count++,若遍历到的字符不是字母,则直接结束循环,返回count

  1. char[] cs = s.toCharArray();
  2. int i = cs.length - 1;
  3. int count = 0;
  4. boolean flag = false;
  5. while (i>=0) {
  6. if ((cs[i] >= 65 && cs[i] <= 90) || (cs[i] >= 97 && cs[i] <= 122)) {
  7. count++;
  8. flag = true;
  9. }else{
  10. if(flag){
  11. break;
  12. }
  13. }
  14. i--;
  15. }
  16. return count;

2、官方题解

官方题解采用的也是反向遍历的操作,和我的思路是一样的,只是代码稍有不同

  1. class Solution {
  2. public int lengthOfLastWord(String s) {
  3. int index = s.length() - 1;
  4. while (s.charAt(index) == ' ') {
  5. index--;
  6. }
  7. int wordLength = 0;
  8. while (index >= 0 && s.charAt(index) != ' ') {
  9. wordLength++;
  10. index--;
  11. }
  12. return wordLength;
  13. }
  14. }
  15. 作者:力扣官方题解
  16. 链接:https://leetcode.cn/problems/length-of-last-word/
  17. 来源:力扣(LeetCode)
  18. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号