当前位置:   article > 正文

leetcode 58. 最后一个单词的长度

leetcode 58. 最后一个单词的长度

Problem: 58. 最后一个单词的长度

文章目录

方案

逆转,然后从非空字符查找,找到空字符,则l-i,没找到空字符,s.length()-i

https://leetcode.cn/problems/length-of-last-word/solutions/2717428/58-zui-hou-yi-ge-dan-ci-de-chang-du-by-s-t2ul/

Code

class Solution {
public:
    int lengthOfLastWord(string s) {
        reverse(s.begin(), s.end());
        int i = 0;
        while(s[i]==' ') {i++;}
        int l = s.find(' ', i);
        return l==-1? s.length()-i:l - i;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/872138
推荐阅读
相关标签
  

闽ICP备14008679号