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

2017-11-25  本文已影响0人  小双2510

原题是:

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'
上一篇下一篇

猜你喜欢

热点阅读