hdu1274 展开字符串(递归or栈)

来源:互联网 发布:vod点播软件 编辑:程序博客网 时间:2024/06/05 16:12

题意:展开
1(1a2b1(ab)1c)= abbabc
3(ab2(4ab))= abaaaabaaaababaaaabaaaababaaaabaaaab
类似的具有 在括号里面,递归特性的的字符串。
思路:对于每个括号里面都具有类似特性,明显对于每个括号里递归处理或者借助栈,原理都是一样的,递归算是借用系统的栈。码力很弱,搞了几天,最后还在我们oj上出了一道类似的,最后把两种代码记载一下,原理看代码就清楚。
借用栈:
思路:
判断当前位置:
1.如果是数字和左括号,就直接进栈。
2.如果是字母,判断一下栈顶是数字吗?如果是说明是字母前的数字,但是这里注意,数字 可能是多位数 。在很多别人AC的代码里没注意这一点,最后也能AC,只能说这题数据很弱。
3.如果是右括号,就要对栈里左括号之前的东西复制括号前的次数放入栈里。

#include<bits/stdc++.h>using namespace std;int main(){    int T;cin>>T;    while(T--){        string s,ans;cin>>s;        stack<char>sta;        for(int i=0;i<s.size();i++){           if(s[i]>='0'&&s[i]<='9'||s[i]=='(') sta.push(s[i]);           else if(isalpha(s[i])){              if(sta.top()>='0'&&sta.top()<='9'){                  int t=10;                  int num=sta.top()-'0'; sta.pop();                  while(!sta.empty()&&sta.top()>='0'&&sta.top()<='9'){                      num=num+t*(sta.top()-'0');                      sta.pop();                      t*=10;                  }                  while(num--){                    sta.push(s[i]);                  }              }              else sta.push(s[i]);           }           else if(s[i]==')'){              string temp;              while(sta.top()!='('){                temp.insert(temp.begin(),sta.top());                sta.pop();              }              sta.pop();              int num;              if(sta.empty()||!(sta.top()>='0'&&sta.top()<='9')) num=1;              else{                  int t=10;                  num=sta.top()-'0'; sta.pop();                  while(!sta.empty()&&sta.top()>='0'&&sta.top()<='9'){                      num=num+t*(sta.top()-'0');                      sta.pop();                      t*=10;                  }              }              while(num--){                 for(int j=0;j<temp.size();j++) sta.push(temp[j]);              }           }        }        while(!sta.empty()){            ans.insert(ans.begin(),sta.top());            sta.pop();        }        cout<<ans<<endl;    }}

递归:

#include<bits/stdc++.h>using namespace std;int i;string str(string s){    string temp="";    int num=0;    for(;i<s.size();i++){        if(s[i]>='0'&&s[i]<='9') num=num*10+s[i]-'0';        else if(isalpha(s[i])){            if(s[i-1]>='0'&&s[i-1]<='9'){                for(int j=0;j<num;j++){                    temp+=s[i];                }                num=0;            }            else temp+=s[i];        }        else if(s[i]=='('){            if(isalpha(s[i-1])) num=1;            i++;            string t=str(s);            for(int j=0;j<num;j++) temp+=t;            num=0;        }        else return temp;    }}int main(){    int T;cin>>T;    while(T--){        i=0;        string s;cin>>s;        cout<<str(s)<<endl;    }}
0 0
原创粉丝点击