leetcode 剑指 Offer 58 - I. 翻转单词顺序

题目要求

输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。

解题思路

方法一:双指针

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        # 去除首尾空格
        s = s.strip()
        res = []
        # 定义双指针
        i, j = len(s) - 1, len(s) - 1
        while i >= 0:
            while i >= 0 and s[i] != ' ':
                i -= 1
            res.append(s[i+1: j+1])
            while s[i] == ' ':
                i -= 1
            j = i
        # 以空格为分隔将列表转为字符串输出
        return ' '.join(res)

方法二:python字符串操作

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        # 去除首尾空格
        s = s.strip()
        # 去除中间空格换行等符号
        temp = s.split()
        # 数组反转
        temp.reverse()
        # 以空格为分隔将列表转为字符串输出
        return ' '.join(temp)

知识点

  1. strip():去除首尾空格
    Python strip()方法
  2. split():去除字符串中间空格换行等符号
    Python split()方法
  3. reverse():数组反转
    Python List reverse()方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值