zoukankan      html  css  js  c++  java
  • LeetCode344:Reverse String@Python

    Write a function that takes a string as input and returns the string reversed.

    Example:
    Given s = "hello", return "olleh".

    在这里介绍python中字符串翻转的几种方法:

    1.步长为-1的切片操作。

    1 class Solution(object):
    2     def reverseString(self, s):
    3         """
    4         :type s: str
    5         :rtype: str
    6         """
    7         return s[::-1]

     2.交换前后字母位置。

     1 class Solution(object):
     2     def reverseString(self, s):
     3         """
     4         :type s: str
     5         :rtype: str
     6         """
     7         t = list(s)  
     8         l = len(t)  
     9         for i,j in zip(range(l-1, 0, -1), range(l//2)):  
    10             t[i], t[j] = t[j], t[i]  
    11         return "".join(t)
    zip函数可参见文档:http://python.usyiyi.cn/translate/python_278/index.html
    zip([iterable, ...])

    该函数返回一个以元组为元素的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。返回的列表长度被截断为最短的参数序列的长度。当多个参数都具有相同的长度时,zip()类似于带有一个初始参数为Nonemap()只有一个序列参数时,它返回一个1元组的列表。没有参数时,它返回一个空的列表。

    3. 递归的方式, 每次输出一个字符。
    1 class Solution(object):
    2     def reverseString(self, s):
    3         """
    4         :type s: str
    5         :rtype: str
    6         """
    7         if len(s) <= 1:  
    8             return s  
    9         return reverseString(s[1:]) + s[0]  

    4. 双端队列, 使用extendleft()函数

     1 from collections import deque  
     2 class Solution(object):
     3     def reverseString(self, s):
     4         """
     5         :type s: str
     6         :rtype: str
     7         """
     8         d = deque()  
     9         d.extendleft(s)  
    10         return ''.join(d)

    5.使用for循环, 从左至右输出

    1 class Solution(object):
    2     def reverseString(self, s):
    3         """
    4         :type s: str
    5         :rtype: str
    6         """
    7         return ''.join(s[i] for i in range(len(s)-1, -1, -1)) 

    以上内容参见博客:http://blog.csdn.net/caroline_wendy/article/details/23438739

    我在LeetCode上提交的是:

     1 class Solution(object):
     2     def reverseString(self, s):
     3         """
     4         :type s: str
     5         :rtype: str
     6         """
     7         l=len(s)
     8         if l>0:
     9             str=s[l-1]
    10             while l!=1:
    11                 l-=1
    12                 str=str+s[l-1]
    13         else:
    14             return s
    15         return str
  • 相关阅读:
    窗口与窗口之间的关系
    线程同步机制--信号量
    c++的静态变量与静态函数
    MFC实现普通DLL
    常规DLL与扩展DLL区别
    pyget-资源与标签(Sprite、Label、Font)
    linux如何添加系统环境变量
    nginx 入门 安装
    redis基本用法
    linux安装 redis
  • 原文地址:https://www.cnblogs.com/mzct123/p/5793702.html
Copyright © 2011-2022 走看看