1. 程式人生 > >leetcode 58. Length of Last Word

leetcode 58. Length of Last Word

思路:可以倒著找非空格字元,並用變數count統計連續非空字元數量。

注意考慮到字串全為空格的情況。

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s == ""){
            return 0;
        }
        int count = 0;
        int i;
        for(i = s.size()-1;i>=0;--i){
           if((s[i] == ' ') &&  (count != 0)){//統計值不為0並且再次碰到空格停止
               return count;
           }else if(s[i] != ' '){	
               count++;
           }
        }
       return count;//當輸入為空字串的時候,返回為0
    }
};