Minimum number of bracket reversals needed to make an expression balanced
given an expression only containing ‘{’ and ‘}’, find a solution to determine the minimum number of bracket reversals needed to make the given expression balanced.
hints:
- only even number has solution
- reversal operations only needed for mismatched bracket
- remaining mismatched brackets must be a even number.
sample code
int minReversalCount(string exp)
15 {
16 int n = exp.length();
17 if (n <= 0) return 0;
18 if (n & 0x1) return -1; //only even length is valid
19 stack<char> st;
20
21 //remove matched brackets by stack
22 for (int i = 0; i < n; i++)
23 {
24 if (!st.empty() && exp[i] == '}')
25 {
26 if (st.top() == '{')
27 {
28 st.pop();
29 }
30 else
31 {
32 st.push(exp[i]);
33 }
34 }
35 else
36 {
37 st.push(exp[i]);
38 }
39 }
40
41 int lefted = st.size(); // the remaining number must be even.
42 int m = 0;
43 while (!st.empty())
44 {
45 if (st.top() == '{') ++m;
46 st.pop();
47 }
48 return (lefted >> 1)+ (m & 0x1);
49 }
iterative traversal of graph
suppose the graph is connected , all nodes is reachable. Depth first traversal needs a stack to store the adjacent node. With stack push and pop , nodes in deepest is visited. In case of visiting a node twice, all visited node should be marked. the following is sample code.
class Graph
{
int mVertex;
vector<int> *mAdjList; // adjacency vectors
public:
Graph(int mVertex); // Constructor
void addEdge(int v, int w); // to add an edge to graph
void DFS(int s); // prints DFS from a given source s
};
Graph::Graph(int vertex) : mVertex(vertex)
{
mAdjList = new vector<int>[mVertex]; //check status needed
}
void Graph::addEdge(int v, int w)
{
mAdjList[v].push_back(w); // Add w to v’s vector.
}
void Graph::DFS(int s)
{
vector<int> visited(mVertex,false);
stack<int> stack;
visited[s] = true;
stack.push(s);
vector<int>::iterator i;
while (!stack.empty())
{
s = stack.top();
cout << s << " ";
stack.pop();
for (i = mAdjList[s].begin(); i != mAdjList[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
stack.push(*i);
}
}
}
}