1. 程式人生 > >4.2.2 LeetCode字串類題目選做(2)—— Length of Last Word & Reverse Words in a String

4.2.2 LeetCode字串類題目選做(2)—— Length of Last Word & Reverse Words in a String

這一節也是對字串的一些簡單處理,而且都是處理word,難度都不大,做一做這類題有點像NLP工程師。

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

題目解析:

flag這種操作在刷題時很常見,記錄一個狀態,上一個字元為空格且該字元不為空格,flag設定為0,並開始計數,flag初始狀態也是0.題目比較簡單,程式碼如下:

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        word = 0
        flag = 0
        for char in s:
            if char == ' ':
                flag = 1 
            elif flag and char != ' ':
                word = 1
                flag = 0
            else:
                word += 1
        return word

151. Reverse Words in a String

Given an input string, reverse the string word by word.

Example:  

Input: "the sky is blue",
Output: "blue is sky the".

Note:

A word is defined as a sequence of non-space characters.

Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.

You need to reduce multiple spaces between two words to a single space in the reversed string.

題目解析:

接著上一題,此題也是處理單詞的,記錄所有單詞,並逆序輸出。方法一,使用遍歷字串的思想去做,也方便後續其他語言(Java)的學習;方法二,使用python的函式,十分快捷,而且速度也極快,split函式的實現方法有待調研。另外,單詞列表的逆序,我們也用了python的特色寫法,用python 還是要pythonic,畢竟原始碼的實現比我們自己寫的快。

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack = []
        word = ""
        for char in s:
            if char == " ":                
                if len(word):
                    stack.append(word)
                word = ""    
            else:
                word += char
        if len(word):
            stack.append(word)
        
        stack = stack[::-1]
        return " ".join(stack)
class Solution(object):
    def reverseWords(self, s):
        word_list = [ele for ele in s.strip().split(' ') if ele]
        list_ = word_list[::-1]        
        ret = ' '.join(list_)
        return ret