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

思路很簡單,先過濾最後的空格,然後在根據字符不是空格來求最後一個單詞的長度
c++:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int right = s.size() - 1;
        int res = 0;
        while(right >= 0 && s[right] == ' ') --right;
        while(right >= 0 && s[right] != ' '){
            --right;
            res++;
        }
        return res;
    }
};

java:

class Solution {
    public int lengthOfLastWord(String s) {
        int right = s.length() - 1;
        int res = 0;
        while(right >= 0 && s.charAt(right) == ' ') --right;
        while(right >= 0 && s.charAt(right) != ' '){
            --right;
            res++;
        }
        return res;
    }
}

python:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        right = len(s) - 1;
        res = 0
        while right >= 0 and s[right] == ' ': right -= 1
        while right >= 0 and s[right] != ' ':
            right -= 1
            res += 1
        
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章