美文网首页
[easy][String][Two-pointer]344.R

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

作者: 小双2510 | 来源:发表于2017-11-25 22:12 被阅读0次

    原题是:

    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'
    

    相关文章

      网友评论

          本文标题:[easy][String][Two-pointer]344.R

          本文链接:https://www.haomeiwen.com/subject/bilhbxtx.html