使括号平衡的最小交换次数

描述:

给定 2N 长度的字符串,包含N个 '[' ,N个 ']',计算使字符串平衡的最小交换次数

平衡字符串定义:S1[S2], 其中 S1,S2均为平衡字符串

输入:

2N长度字符串

输出:

最小交换次数

举例:

Input : []][][

Output : 2

First swap: Position 3 and 4 [][]][

Second swap: Position 5 and 6 [][][]

Input : [[][]]

Output : 0

String is already balanced.

Solution is below

思路

顺序遍历字符串,当遇到不匹配的']'时(遇到相应的'['之前),将其与之后最接近它的']'交换位置

实现

Last updated