leetcode:58 Length of Last Word-每日編程第三十四題

Length of Last Word

Total Accepted: 76106 Total Submissions: 269840 Difficulty: Easy

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.

For example, 
Given s = "Hello World",
return 5.


<span style="font-size:12px;">class Solution {
public:
    int lengthOfLastWord(string s) {
        int len=s.length();
        //判斷是否爲空字符串
        if(len==0){
            return 0;
        }
        int index=len-1;
        //去掉末尾可能出現的空格
        while(index>=0&&s[index]==' '){
            index--;
        }
        //ans爲最後一個字符長度
        int ans=0;
        while(index>=0&&s[index]!=' '){
            index--;
            ans++;
        }
        return ans;
    }
};</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章