[easy][String][Two-pointer]344.Reverse String

原题是:

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

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

思路是:

两个指针分别从开头和结尾,向中间移动。
互换两个指针的元素,直到两个指针相遇。
就可以reverse整个list.

代码是:

class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        # if not s:
        #     return s
        strList = list(s)
        i = 0
        j = len(strList) -1 
        while i < j:
            tmp = strList[i]
            strList[i] = strList[j]
            strList[j] = tmp
            i += 1
            j -= 1
        
        return ''.join(strList)

其中,string和list的转换:

import string
str = 'abcde'
 list = list(str)
list
['a', 'b', 'c', 'd', 'e']
str
'abcde'
str_convert = ''.join(list)
str_convert
'abcde'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容