Leetcode length of last word

Source: Internet
Author: User

Question: a string containing only uppercase and lowercase letters and spaces. Returns the length of the last word. "ABC a" is 1 "ABC" is 3

There are two ideas: one from the beginning and the other from the back.

1. Remember the length of a word before the space from the beginning to the end. If there is a space to the end, output the record value. If there is a word after the space, count it again. Use flag to record whether spaces are encountered.

class Solution {public:    int lengthOfLastWord(const char *s)     {        int flag = 0, cnt = 0;        while(*s != ‘\0‘)        {            if (flag) {cnt = 0; flag = 0;}            while (*s != ‘\0‘ && *s != ‘ ‘) {cnt++;s++;}            while (*s != ‘\0‘ && *s == ‘ ‘) {s++;flag = 1;}        }        return cnt;    }};

2. From the back to the front, first determine the last pointer, and then return the result after hitting the space after the first word.

class Solution {public:    int lengthOfLastWord(const char *s)     {        const char *p = s + strlen(s) - 1;        int cnt = strlen(s), t = 0;        while(cnt > 0)        {            if (*p == ‘ ‘) {p--; cnt--;continue;}            if (cnt > 0 && *p != ‘ ‘)            {                while(cnt > 0 && *p != ‘ ‘)                {                    t++;cnt--;p--;                }                return t;            }        }        return 0;    }};


Leetcode length of last word

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.