stack related algorithms summary

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 }

original solutions

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);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值