题解 | #字符串解码#
字符串解码
https://www.nowcoder.com/practice/4e008fd863bb4681b54fb438bb859b92?tpId=117&tqId=39388&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D5%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D117&difficulty=undefined&judgeStatus=undefined&tags=&title=
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串 */ string decodeString(string s) { // write code here int n = s.size(); stack<char> st; for (int i = 0; i < n; ++i) { if (s[i] == ']') { string str = "", num = ""; while (!st.empty() && st.top() != '[') { str = st.top() + str; st.pop(); } st.pop(); while (!st.empty() && isdigit(st.top())) { num = st.top() + num; st.pop(); } int n = num == "" ? 1 : stoi(num); for (int j = 0; j < n; ++j) { for (const auto &ch : str) { st.emplace(ch); } } } else { st.emplace(s[i]); } } string ans; while (!st.empty()) { ans = st.top() + ans; st.pop(); } return ans; } };