翻转算法

时间:2016-11-09 10:32:55

标签: string algorithm brackets balance

我有一个包含不同类型括号的字符串s()[]。如何平衡此类型的字符串与最小可能的反转次数?我可以用任何其他支架替换任何支架。

例如:[)(]的费用为2,变为[()][]((的费用为1,变为[]()[(])不平衡。

一个更复杂的示例:)[)([)())]可以在4次更改中转为([])[(())],但也可以通过3个步骤转为[()(()())],这是最少的修改次数它平衡了。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

我带来的第一种方法是O(n^3)动态编程。

match(i, j)s[i]s[j] ()[]所需的替换次数。因此match(i, j)可以是012

考虑dp[i][j] = the minimum cost to balance the subsequence from i to j in your brackets array。现在,您将dp[i][i + 1]定义为:

dp[i][i + 1] = match(i, i + 1)

现在一般规则是,对于任何dp[i + 1][j - 1] + match(i, j),我们会将min(dp[i][j], dp[i][p] + dp[p + 1][j])i < p < j之间的总体最小值设为最小值。显然,结果将保存在dp[1][n]中。有一个C ++解决方案(我将在大约15分钟内上传一个python程序,当我完成它时 - 用python:P不太强大。)

#include <iostream>
#include <string>
using namespace std;

int dp[100][100];
string s;
int n;

int match(char a, char b) {
    if (a == '(' && b == ')') {
        return 0;
    }
    if (a == '[' && b == ']') {
        return 0;
    }
    if ((a == ')' || a == ']') && (b == '(' || b == '[')) {
        return 2;
    }
    return 1;
}

int main() {
    cin >> s;
    n = s.length();
    s = " " + s;
    for (int i = 0; i <= n; ++i) {
        for (int j = 0; j <= n; ++j) {
            dp[i][j] = 0x3f3f3f3f;
        }
    }    

    for (int i = 1; i < n; ++i) {
        dp[i][i + 1] = match(s[i], s[i + 1]);
    }

    for (int k = 3; k <= n; k += 2) {
        for (int i = 1; i + k <= n; ++i) {
            int j = i + k;
            dp[i][j] = min(dp[i][j], dp[i + 1][j - 1] + match(s[i], s[j]));
            for (int p = i + 1; p <= j; p += 2) {
                dp[i][j] = min(dp[i][j], dp[i][p] + dp[p + 1][j]);
            }
        }
    }
    cout << dp[1][n] << '\n';
    /*for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            cout << dp[i][j] << ' ';
        }
        cout << '\n';
    }*/
    return 0;
}

编辑:

在这里你去Python:)

s = input()
n = len(s)
inf = 0x3f3f3f3f

def match(x, y):
    if x == '(' and y == ')':
        return 0
    if x == '[' and y == ']':
        return 0
    if (x == ')' or x == ']') and (y == '(' or y == '['):
        return 2
    return 1

# dp[i][j] = min. cost for balancing a[i], a[i + 1], ..., a[j]
dp = [[inf for j in range(n)] for i in range(n)]

for i in range(n - 1):
    dp[i][i + 1] = match(s[i], s[i + 1])

for k in range(3, n, 2):
    i = 0
    while i + k < n:
        j = i + k
        dp[i][j] = min(dp[i][j], dp[i + 1][j - 1] + match(s[i], s[j]))
        for p in range(i + 1, j, 2):
            dp[i][j] = min(dp[i][j], dp[i][p] + dp[p + 1][j])
        i += 1

print(dp[0][n - 1])
#for i in range(n):
#    for j in range(n):
#        print(dp[i][j], end = ' ')
#    print()