致我们终将忘记的算法(栈的伤)

1->栈在括号匹配中的应用,一个字符串仅包含"(",")","["."]","{"."}"这三种字符,判断这个字符串中的括号是否匹配

解题方法:利用栈的先进后出的功能

bool isValid(string const& s){

    string leftstr="([{";

    string rightstr=")]}";

    stack<char> stk;

    for(string::iterator c=s.begin();c!=s.end();c++){

        if(leftstr.find(*c)!=string::npos){

              stk.push(*c);

        }else{

               if(stk.empty()||stk.top()!=leftstr[rightstr.find(*c)])   return false;

               else  stk.pop();

        }

    }

    return stk.empty();

}

2->求一个只包含“)”和“(”字符的最大匹配长度。例如:“(()”最大匹配为“()”返回长度为2

int longestValidParentheses(string s){

    int max_len=0,last=-1;     //最后一个‘)’的位置

    stack<int> lefts;

    for(int i=0;i<s.size();i++){

        if(s[i]=='(')   lefts.push(i);

        else{

             if(lefts.empty())  last=i;

             else{

                 lefts.pop();

                if(left.empty()){

                     max_len=max(max_len,i-last);

                 else

                    max_len(max_len,i-lefts.top());

                }

             }

        }

    }

    return max_len;

}

3->求后续表达式的值。例如:["2","1","+","3","*"]返回(2+1)*3=9

int evalRPN(vector<string>& tokens){

    stack<string> s;

    for(int i=0;i<tokens.size();i++){

          if(!is_operator(tokens[i]))   s.push(tokens[i]);

          else{

               int y=stoi(s.top());  s.pop();

               int x=stoi(s.top()); s.pop();

               if(tokens[i]=='+')   x+=y;

               else if(tokens[i]=='-')  x-=y;

               else if(tokens[i]==‘*')  x*=y;

               else x/=y;

               s,push(to_string(x));

          }

    }

    return stoi(s.top());

}

发布了99 篇原创文章 · 获赞 8 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/CodeAsWind/article/details/39159529