题目:字符串解码
python 栈
1. append()
>>> testList = [123, 'xyz', 'zara', 'abc'];
>>> testList.append( 'hrzgj' )
>>> testList
[123, 'xyz', 'zara', 'abc', 'hrzgj']
>>> testList.append([1,2,'nb'])
>>> testList
[123, 'xyz', 'zara', 'abc', 'hrzgj', [1, 2, 'nb']]
>>>
2. pop()
语法: list.pop(obj=list[-1])
; 返回: list[-1]
>>> testList = [123, 'xyz', 'zara', 'abc'];
>>> testList.pop()
'abc'
>>> testList
[123, 'xyz', 'zara']
>>> testList.pop(0)
123
>>> testList
['xyz', 'zara']
py3中字符串数字比较大小
字符串按位比较,两个字符串第一位字符的ascii码谁大,字符串就大,不再比较后面的;
第一个字符相同就比第二个字符串,以此类推。
ascii码
数字:
0-9: 48-57
字母:
A-Z:65-90
a-z: 97-122
空(null):0
空格: 32
注: 一串数字、字符的 ASCII 码值大小取决于最后一位的 ASCII 码值,
例如:
123454 的ASCII 码值为 52
4 的 ASCII码值 也为 52
ABCDA 为 65
A 也是 65
题目描述
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
题目分析
n*[] + 无乘数的
3*a + 2*[bc]
3*[2*c]
2*[abc] + 3*[cd] + ef
- 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算;
- 当 c 为字母时,在 res 尾部添加 c;
- 当 c 为 [ 时,将当前 multi 和 res 入栈,并分别置空置 0。
- 当 c 为 ] 时,stack 出栈,拼接字符串
代码示例:
def decodeString(s):
stack, multi, res = [], 0, ""
for c in s:
# print(c)
if c == '[':
stack.append([multi, res])
print(stack) # [[multi, res]] ---> 2D
multi, res = 0, ""
elif c == ']':
print(stack)
cur_multi, last_res = stack.pop()
res = last_res + cur_multi * res
elif '0' <= c <= '9':
multi = multi * 10 + int(c)
else:
res += c
return res