• leetcode 58. length of last word


    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

    If the last word does not exist, return 0.

    Note: A word is defined as a character sequence consists of non-space characters only.

    For example, 
    Given s = "Hello World",
    return 5.

    从头开始记录字符串的长度,如果是最后一个字符串输出。

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int n=s.length();
            int l=0;
            int l_pre=0;
            for(int i=0;i<n;i++)
            {
                
                if(s[i]==' ')
                {
                    if(l!=0)
                    l_pre=l;
                     l=0;
                }
                   
                else l++;
            }
            if(l==0)
                return l_pre;
            else
            return l;
        }
    };
    

      

    只有后面是字符串的话,才改变length 为0

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int n=s.length();
            int l=0;
            bool start=true;
            for(int i=0;i<n;i++)
            {
                
                if(s[i]!=' ')
                {
                    if(start) l=0;
                    l++;   
                    start=false;
                }
                else
                    start=true;
                   
            }
       
            return l;
        }
    };
  • 相关阅读:
    4.23上机练习
    4.17java作业
    4.16java作业
    leetcode 189
    leetcode 172
    leetcode 171
    leetcode 169
    win10内网外网智能访问
    leetcode 168
    leetcode 165
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7222181.html
Copyright © 2020-2023  润新知