zoukankan      html  css  js  c++  java
  • 422. 最后一个单词的长度

    422. 最后一个单词的长度

    给定一个字符串, 包含大小写字母、空格' ',请返回其最后一个单词的长度。

    如果不存在最后一个单词,请返回 0 。

    class Solution {
    public:
        /*
         * @param s: A string
         * @return: the length of last word
         */
        int lengthOfLastWord(string &s) {
        // write your code here
            int size = s.length();
        //找到最后一个不是空格的字母
            bool isStart = false;
            int length = 0;
            for (int i = size - 1; i >= 0; i--) {
                if (check(s[i])) {
                    if (!isStart) {
                        isStart = true;
                    }
                    length++;
                } else {
                    if (isStart) {
                        return length;
                    }
                }
            }
            return length;
        }
        
        
        bool check(char ch) {
            if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
                return true;
            return false;
        }
    
    };
    

      

  • 相关阅读:
    hero
    今年暑假不AC
    Who's in the Middle
    A Simple Problem with Integers
    I hate it
    敌兵布阵
    Ordering Tasks
    Points on Cycle
    食物链
    c++ 14.0下载地址
  • 原文地址:https://www.cnblogs.com/kanekiken/p/7985569.html
Copyright © 2011-2022 走看看