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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值