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
- hdu1274 展开字符串(递归or栈)
- hdu1274展开字符串(递归)
- HDU1274 展开字符串【栈】
- hdu1274 展开字符串(DFS)
- hdu1274 展开字符串(C语言)
- HDU1274:展开字符串
- HDU1274 展开字符串
- hdu1274 展开字符串
- HDU1274 展开字符串
- ACM-递归之展开字符串——hdu1274
- hdoj 1274 展开字符串(递归,栈的应用)
- 字符串展开(递归)hdu 1274
- HDU 1274 展开字符串(递归)
- HDU1274 非递归做法
- hdoj 展开字符串 1274 (字符串递归) 好题
- HDU 1274 展开字符串 (递归+string类)
- hdu1274
- hdu1274
- 2016/4/16
- 1.UIRoot:根据高度自适应屏幕分辨率。
- spring webflow : 上传单个文件实例
- node.js使用回调实现一个简单的HTTP服务器
- POJ 3259 Wormholes
- hdu1274 展开字符串(递归or栈)
- 面向对象编程三大特征
- 汽车之家移动主App服务端架构变迁
- 使用caffe的convert_imageset生成lmdb文件
- Linux下Samba服务器的搭建
- Linux 忘记root密码
- 单源多点最短路径-Dijkstra算法
- 关于微信安卓版计步作弊器
- view 使用 setTag() 和getTag方法