zoukankan      html  css  js  c++  java
  • 刷题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.
    

    三、优化措施

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    五、excel末尾补0和开头补0
    MYSQL查询前30条数据
    MYSQL数据库从A表把数据插入B表
    测试用例大全
    EXTJS 5.0 资料
    fs event_socket
    centos 编译swoole
    Valgrind简单用法
    linux 大并发下 内核优化
    FS拓展设置
  • 原文地址:https://www.cnblogs.com/siweihz/p/12331051.html
Copyright © 2011-2022 走看看