我想在这个revers题中使用stack的方法得到reverse string。
“编写一个函数 revstring(mystr),它使用堆栈来反转字符串中的字符。”
这是我的代码。
from pythonds.basic.stack import Stack
def revstring(mystr):
myStack = Stack() //this is how i have myStack
for ch in mystr: //looping through characters in my string
myStack.push(ch) //push the characters to form a stack
revstr = '' //form an empty reverse string
while not myStack.isEmpty():
revstr = revstr + myStack.pop() //adding my characters to the empty reverse string in reverse order
return revstr
print revstring("martin")
输出似乎只打印出 mystr 的第一个字母“m” 这是为什么??
请您参考如下方法:
针对同一问题,这里有 3 种解决方案,只需选择一种即可:
第一个解决方案
修复你的解决方案,你几乎搞定了,你只需要正确缩进 你的 block 是这样的:
from pythonds.basic.stack import Stack
def revstring(mystr):
myStack = Stack() # this is how i have myStack
for ch in mystr: # looping through characters in my string
myStack.push(ch) # push the characters to form a stack
revstr = '' # form an empty reverse string
while not myStack.isEmpty():
# adding my characters to the empty reverse string in reverse order
revstr = revstr + myStack.pop()
return revstr
print revstring("martin")
第二个解决方案
这个在结构上与你的相同,但不是使用自定义堆栈,而是使用内置的 python 列表
def revstring(mystr):
myStack = [] # this is how i have myStack
for ch in mystr:
myStack.append(ch) # push the characters to form a stack
revstr = '' # form an empty reverse string
while len(myStack):
# adding my characters to the empty reverse string in reverse order
revstr = revstr + myStack.pop()
return revstr
print revstring("martin")
第三种解决方案
要反转字符串,只需使用这种 pythonic 方式:)
print "martin"[::-1]
