Compressed Words?
Description
Steve has come up with a way to compress text, though it may not actually compress the text. Steve considers only individual words, and uses the following rules to define a “compressed word”:
a single, lower-case letter is a compressed word
(e1 e2…et n) where t and n are non-negative integers and ei is a compressed word.
You should observe that a compressed word of one character is the same as an uncompressed word. To uncompress the compressed word (e1 e2…et n) we uncompress each ei, concatenate those uncompressed words into a new word, and repeatedly concatenate that word n times. For example:
x would be uncompressed as x,
(t 3) would be uncompressed as ttt,
(a(bc2)3) would be uncompressed as abcbcabcbcabcbc.
Write a program to uncompress a compressed word.
Input
Your program will be tested on one or more test cases. Each test case is made of one correctly formed compressed word on a separate line. A $ character identifies the end of line. The last line of the input, which is not part of the test cases, contains a $ by itself (possibly with leading and/or trailing white spaces). Every compressed word in the input is correct according to the rules specified above. Note that a compressed word may contain leading, trailing, and/or embedded spaces. Such spaces should be ignored. Letters and numbers are separated from each other by at least one space character.
Output
For each test case (i.e., each compressed word), write the uncompressed word on a separate line. There should be no spaces (other than newlines) in the output.
Samples
Input 复制
x$
(t 3)$
( a ( b c 2 ) 3) $
$
Output
x
ttt
abcbcabcbcabcbc
本题是后缀表达式的变式,处理方式与后缀表达式求值相同,用栈解决该问题
Code:
#include<bits/stdc++.h>
#define bug(x) cout<< #x <<" = "<< x <<endl;
using namespace std;
typedef long long ll;
typedef pair<int,int> PI;
const int N = 1e5 + 10;
const int mod = 2147483648;
string s,res;
stack<char> st;
int main() {
while(getline(cin,s) && s[0]!='$') {
res.clear();
while(!st.empty()) st.pop();
int len = s.size();
for(int i=0; i<len; i++) {
if(s[i]=='$') break;
if(s[i]==')') {
int nn = 0;
string tep,sum;
while(!st.empty()) {
char ch = st.top();
st.pop();
if(ch == '(') break;
if(ch>='0' && ch<='9') sum += ch;
if(ch>='a' && ch<='z') tep += ch;
}
for(int j=sum.size()-1; j>=0; j--) nn = nn * 10 + sum[j] - '0';
reverse(tep.begin(),tep.end());
for(int j=0; j<nn; j++)
for(int k=0; k<tep.size(); k++)
st.push(tep[k]);
} else if(s[i]!=' ') st.push(s[i]);
}
while(!st.empty()) res += st.top(),st.pop();
reverse(res.begin(),res.end());
cout<<res<<endl;
}
return 0;
}
/*
x$
(t 3)$
( a ( b 12) 3) $
$
*/