• 刷题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.
    

    三、优化措施

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    Windows平台使用Gitblit搭建Git服务器图文教程
    yapi部署文档
    Yapi学习笔记
    利用微软认知服务实现语音识别功能
    对.Net Core结合Docker和Jexus的实践
    python-集合、字典
    python-文件操作
    python-函数
    python-运算、分支、深浅拷贝
    linux下的文件结构
  • 原文地址:https://www.cnblogs.com/siweihz/p/12331051.html
Copyright © 2020-2023  润新知