刷題394. Decode String

一、題目說明

題目394. Decode String,給定一個編碼後字符串,解碼字符串。難度是Medium!

二、我的解答

解析字符串,這個題目是棧的典型應用。唯一的複雜度在於嵌套的處理。

class Solution{
	public:
		string decodeString(string s){
			stack<char> st;
			stack<int> st_r;
			int repeat = 0,index=0;
			string res;
			int toStack = 0;
			while(index < s.size()){
				char c = s[index];
				
				if(c>='0' && c<='9'){
					repeat = repeat * 10 + (c -'0');
				}else if(c=='['){
					st.push(c);
					st_r.push(repeat);
					repeat = 0;
					toStack++;
				}else if(c==']'){
					string cur;
					repeat = st_r.top();
					st_r.pop();

					while(!st.empty() && st.top()!='['){
						cur.push_back(st.top());
						st.pop();
					}
					st.pop();
					reverse(cur.begin(),cur.end());
					if(toStack > 1){
						while(repeat>0){
							for(int i=0;i<cur.size();i++){
								st.push(cur[i]);
							}
							repeat--;
						}
					}else{
						while(repeat>0){
							res.append(cur);
							repeat--;
						}	
					}
					toStack--;
				}else if(toStack>0){
					st.push(c);
				}else{
					res.push_back(c);
				}
				
				index++;
			}
			return res;
		}
};

性能如下:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Decode String.
Memory Usage: 9 MB, less than 58.82% of C++ online submissions for Decode String.

三、優化措施

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章