1. 程式人生 > >LeetCode算法系列:58. Length of Last Word

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.

Example:

Input: "Hello World"
Output:
5

演算法實現:

非常簡單,只是需要判斷結尾是否有字元為‘ ’,有的話要跳過

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s.empty())return 0;
        int i = s.length() - 1;
        while(s[i] == ' ' && i >= 0)i --;
        if(i < 0)return 0;
        int end = i;
        for(; i >= 0;)
            if(s[i] != ' ') i --;
            else break;
        return end - i;
    }
};