Length of Last Word

来源:互联网 发布:pdf福昕阅读器 mac 编辑:程序博客网 时间:2024/05/16 07:48

理解了题意以后就很简单了。

class Solution {public:    int lengthOfLastWord(const char *s) {        if (s == NULL)            return 0;        int n = strlen(s);        int p = n - 1;        while (p >= 0) {            if (s[p] == ' ')                --p;            else                break;        }        if (p == -1)            return 0;        int last = p;        while (p >= 0) {            if (!isAlpha(s[p]))                break;            --p;        }        return last - p;    }    bool isAlpha(char c) {        if (c >= 'a' && c <= 'z')            return true;        if (c >= 'A' && c <= 'Z')            return true;        return false;    }};

http://oj.leetcode.com/problems/length-of-last-word/

0 0
原创粉丝点击