【HDOJ】1274 展开字符串
栈的应用,需要注意括号前可能没有数字的情况。
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <iostream> 5 #include <stack> 6 #include <string> 7 using namespace std; 8 9 #define MAXN 300 10 #define isdigit(c) (c>='0' && c<='9') 11 #define islower(c) (c>='a' && c<='z') 12 char str[MAXN]; 13 14 void solve() { 15 string ans = ""; 16 stack<char> ops; 17 stack<int> cnts; 18 stack<string> strs; 19 int cnt; 20 int i = 0; 21 22 while (str[i]) { 23 bool found = false; 24 cnt = 0; 25 while (isdigit(str[i])) { 26 cnt = 10*cnt + str[i]-'0'; 27 ++i; 28 found = true; 29 } 30 if (str[i] == '(') { 31 if (!found) 32 cnt = 1; 33 ops.push('('); 34 cnts.push(cnt); 35 strs.push(ans); 36 ans = ""; 37 } else if (str[i] == ')') { 38 cnt = cnts.top(); 39 cnts.pop(); 40 ops.pop(); 41 int r = cnt; 42 string bk = ans; 43 ans = strs.top(); 44 strs.pop(); 45 while (r) { 46 if (r & 1) 47 ans += bk; 48 bk += bk; 49 r >>= 1; 50 } 51 } else { 52 if (found) { 53 string bk(cnt, str[i]); 54 ans += bk; 55 } else { 56 ans += str[i]; 57 } 58 } 59 ++i; 60 } 61 62 cout <<ans<<endl; 63 } 64 65 int main() { 66 int t; 67 #ifndef ONLINE_JUDGE 68 freopen("data.in", "r", stdin); 69 freopen("data.out", "w", stdout); 70 #endif 71 scanf("%d", &t); 72 while (t--) { 73 scanf("%s", str); 74 solve(); 75 } 76 77 return 0; 78 }