程式語言 - LeetCode - C++ - 58. Length of Last Word



題目:


方法:

由後往前找

解答:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int i = s.size() - 1;
        int cnt = 0;

        while ((i >= 0) && (s[i] == ' ')) {
            i -= 1;
        }

        while ((i >= 0) && (s[i] != ' ')) {
            i -= 1;
            cnt += 1;
        }

        return cnt;
    }
};