leetcode 344 python
2017-02-22 20:27
423 查看
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Subscribe to see which companies asked this question
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
b = list(s)
c = len(s)
print("%d",c)
d = []
j = -1
for i in range(1,c+1):
d.append(s[j])
j = j -1
str_convert = ''.join(d)
return str_convert
因为python的read和write方法的操作对象都是string。而操作二进制的时候会把string转换成list进行解析,解析后重新写入文件的时候,还得转换成string。
>>> import string
>>> str = 'abcde'
>>> list = list(str)
>>> list
['a', 'b', 'c', 'd', 'e']
>>> str
'abcde'
>>> str_convert = ''.join(list)
>>> str_convert
'abcde'
class
Solution(object):
def reverseString(self, s):
""" :type s: str :rtype: str """
return s[::-1]
所有数,每5个取一个:
甚至什么都不写,只写
tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
字符串
s1 = list(s)
s1.reverse()
return ''.join(s1)
Example:
Given s = "hello", return "olleh".
Subscribe to see which companies asked this question
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
b = list(s)
c = len(s)
print("%d",c)
d = []
j = -1
for i in range(1,c+1):
d.append(s[j])
j = j -1
str_convert = ''.join(d)
return str_convert
因为python的read和write方法的操作对象都是string。而操作二进制的时候会把string转换成list进行解析,解析后重新写入文件的时候,还得转换成string。
>>> import string
>>> str = 'abcde'
>>> list = list(str)
>>> list
['a', 'b', 'c', 'd', 'e']
>>> str
'abcde'
>>> str_convert = ''.join(list)
>>> str_convert
'abcde'
class
Solution(object):
def reverseString(self, s):
""" :type s: str :rtype: str """
return s[::-1]
所有数,每5个取一个:
>>> L[::5] [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
甚至什么都不写,只写
[:]就可以原样复制一个list:
>>> L[:] [0, 1, 2, 3, ..., 99]
tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
>>> (0, 1, 2, 3, 4, 5)[:3] (0, 1, 2)
字符串
'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:
>>> 'ABCDEFG'[:3] 'ABC' >>> 'ABCDEFG'[::2] 'ACEG'
s1 = list(s)
s1.reverse()
return ''.join(s1)
相关文章推荐
- LeetCode344:Reverse String@Python
- python--leetcode344. Reverse String
- Python [Leetcode 344]Reverse String
- 【python】【leetcode】【算法题目344—Reverse String】
- leetcode344题 题解 翻译 C语言版 Python版
- 【LeetCode with Python】 Remove Duplicates from Sorted List
- 【LeetCode with Python】 Merge Two Sorted Lists
- 【LeetCode with Python】 Remove Duplicates from Sorted Array
- 【LeetCode with Python】 Binary Tree Preorder Traversal
- 【LeetCode with Python】 Maximum Depth of Binary Tree
- 【LeetCode with Python】 Single Number
- 【LeetCode with Python】 Binary Tree Inorder Traversal
- 【LeetCode with Python】 Pow(x, n)
- 【LeetCode with Python】 Maximum Subarray
- 【LeetCode with Python】 Insertion Sort List
- 【LeetCode with Python】 Swap Nodes in Pairs
- 【LeetCode with Python】 Reverse Words in a String
- 【LeetCode with Python】 Linked List Cycle
- 【LeetCode with Python】 String to Integer (atoi)
- 【LeetCode with Python】 Decode Ways