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

猜你喜欢

转载自blog.csdn.net/xutiantian1412/article/details/82961914
今日推荐