leetcode Length of Last Word

4118 ワード

タイトル:大文字と小文字の文字列とスペースのみを含む文字列を指定します.最後の単語の長さを返します.「abc a」は1「abc」は3
二つの考え方は,一つは最初から後ろへ,一つは後ろから前へ.
1.最初から後ろに行く場合は、スペースの前の単語の長さを覚え、最後までスペースがある場合は記録値を出力し、スペースの後に単語がある場合はカウントし直します.flagで知否がスペースに遭遇したかどうかを記録します.
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.後ろから前へ、最後のポインタを決めて、最初の単語にぶつかった後のスペースを返します.
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;

    }

};