[leetcode]length-of-last-word

RioDream發表於2019-05-12

RT

思路:

遇到空格就置計數器為0,遇到非空格就+1,尤其注意“a ”,這種情況,所以設定一個 trash變數,存取上一次被丟棄的計數,如果最後以“ ”結束,就從trash中取出計數。


solution 1

class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int lastWordLength = 0;
        int lastWordLength_trash = lastWordLength; //initialize in case of cases like "   "
        char last = ` `;
        int i=0;
        while(s[i]!=` `){
            char temp = s[i];
            if(temp!=` `){
                lastWordLength++;    
            //}else if(last!=` `&&temp==` `){
            else if(last!=` `){ //比上面這一行更簡潔。
                lastWordLength_trash = lastWordLength;
                lastWordLength=0;
            }
            i++;
            last = temp;
        }
        //avoid cases like "a   "
        if(last==` `){ //get it back from trash
            lastWordLength = lastWordLength_trash;
        }
        return lastWordLength;
    }
};