Decode the string | Practice | GeeksforGeeks

An encoded string (s) is given, the task is to decode it. The pattern in which the strings were encoded were as follows
original string: abbbababbbababbbab 
encoded string : 3[a3[b]1[ab]]
Example 1:
Input: s = 1[b]
Output: b
Explaination: 'b' is present only one time.
Example 2:
Input: s = 3[b2[ca]]
Output: bcacabcacabcaca
Explaination: 2[ca] means 'ca' is repeated 
twice which is 'caca' which concatenated with 
'b' becomes 'bcaca'. This string repeated 
thrice becomes the output.
Your Task:
You do not need to read input or print annything. Your task is to complete the function decodedString() which takes s as input parameter and returns the decoded string.
Expected Time Complexity: O(|s|)
Expected Auxiliary Space: O(|s|)
Constraints:
1 ≤ |s| ≤ 30 
0
jainsakshi09014 days ago
Not an easy one 
0
danish_nitdgp1 week ago
C++ O(n) Solution string decodedString(string s){       // code here       stack<char> st;       for(int i =0;i<s.length();i++){           if(s[i]!=']') st.push(s[i]);           else {               string temp;               while(!st.empty() && st.top()!='['){                   temp = st.top() + temp;                   st.pop();               }               st.pop();               string num;               while(!st.empty() && isdigit(st.top())){                   num = st.top() + num;                   st.pop();               }               int number = stoi(num);               string repeat;               while(number--){                   repeat = repeat + temp;               }               for(char c : repeat) st.push(c);           }       }       string res;       while(!st.empty()){           res = st.top() + res;           st.pop();       }              return res;   }
0
umeshkaushik6103 weeks ago
RECURSIVE SIMPLE APPROACH | C++
class Solution{public:   int i=0;   string decodedString(string s){   int times=0; string res="";       // string s = s;       while(i<s.size()){           if(isdigit(s[i])){               int ch = s[i]-'0';               while(i+1 < s.size() and isdigit(s[i+1])){                   ch = (ch*10) + (s[++i]-'0');               }               // cout<<ch<<" ";               // cout<<endl;               times = ch;           }           else if(s[i] == '['){               i++;                auto tmp = decodedString(s);               while(times--) res+=tmp;           }           else if(s[i] == ']') break;           else{               res += s[i];           }           i++;       }       return res;   }};
0
chauhangaurav97214 weeks ago
class Solution{
public:
    string decodedString(string s){
        stack<string>stk;
        for(int i = 0; i < s.size(); i++){
            if(s[i]==']'){
                string temp = "";
                while(stk.top()!="["){
                    temp = temp + stk.top();
                    stk.pop();
                }
                stk.pop();
                string count = "";
                while(stk.size() && isdigit(stk.top()[0])){
                    count = count + stk.top();
                    stk.pop();
                }
                reverse(count.begin(), count.end());
                int cnt = stoi(count);
                string cur = "";
                while(cnt--) cur += temp;
                stk.push(cur);
            }else{
                stk.push(string(1, s[i]));
            }
        }
        string ans = stk.top();
        reverse(ans.begin(), ans.end());
        return ans;
    }
};
+11
geminicode2 months ago
THIS IS NOT EASY !!!!!!!! 
0
sachinkartik1663 months ago
class Solution{
     String decodedString(String s){
        Stack<String> st=new Stack<>();
        String ans="";
        
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)==']'){
                String pele=st.pop();
                String maker="";
                while(!pele.equals("[")){
                    maker=pele+maker;
                    
                         pele=st.pop();
                   
                   
                }
               
                      pele=st.pop();
                String up="";
                for(int j=0;j<Integer.parseInt(pele);j++){
                    up=maker+up;
                }
                
                st.push(up);
                 
               
                
            }else{
                
            
            try{
                  String pp=st.peek();
                
                if(isNumeric(String.valueOf(s.charAt(i)))){
                    
                
                if(isNumeric(pp)){
                     while(isNumeric(pp)){
                      st.pop();
                      pp=pp+String.valueOf(s.charAt(i));
                      if(!st.isEmpty()){
                           pp=st.peek();
                      }else{
                          break;
                      }
                     
                }
                
                st.push(pp);
                }else{
                    st.push(String.valueOf(s.charAt(i)));
                }
                }else{
                    st.push(String.valueOf(s.charAt(i)));
                }
               
            }catch(Exception e){
                 st.push(String.valueOf(s.charAt(i)));
            }
                   
              
               
            }
       
    }
    
    return st.pop();
    
    }
    
    public  boolean isNumeric(String str) { 
       try {  
          Integer.parseInt(str);  
          return true;
       } catch(NumberFormatException e){  
          return false;  
    }  
}
    
}
+1
suchigiri134 months ago
class Solution{
    static String decodedString(String s){
         Stack<Character> stack = new Stack<>();
        int i = s.length() - 1;

        String ans = "";
        while(i >= 0){
            String temp = "";
            while(s.charAt(i) != '['){
                stack.push(s.charAt(i));
                i--;
            }if(s.charAt(i--) == '[') {
                while (stack.peek() != ']') {
                    temp += stack.pop();
                   // System.out.println(temp);
                }
            }
                stack.pop();
                if(!stack.isEmpty() && i >= 0){
                    temp = temp.repeat(Character.getNumericValue(s.charAt(i)));
                    ans = temp + ans;
                    i--;
                }

                else if(stack.isEmpty() && i >= 0) {
                    if (Character.isDigit(s.charAt(i))) {
                        ans = temp + ans;
                        ans = ans.repeat(Character.getNumericValue(s.charAt(i)));
                        i--;
                    }
                }
        }

        return ans;
    }
}
Can anyone explain to me why it is giving run time error!!
 
+5
lovilakheraa024 months ago
EASY TO UNDERSTAND SOLUTION

class Solution{
public:
   string decodedString(string s){
       // code here
       int currNo=0;
       string currString="";
       int prevNo;
       string prevString;
       stack<string>stringstack;
       stack<int>numstack;
       for(int i=0;i<s.size();i++)
       {
           if(isdigit(s[i])) currNo = currNo*10 + (s[i]-'0');
           if(isalpha(s[i])) currString += s[i];
           if(s[i] == '[')
           {
               stringstack.push(currString);
               numstack.push(currNo);
               currNo=0;
               currString="";
           }
           if(s[i] == ']')
           {
               prevNo = numstack.top();
               numstack.pop();
               prevString = stringstack.top();
               stringstack.pop();
               
               while(prevNo--)
               {
                  prevString += currString;
               }
               currString = prevString;
           }
       }
       return currString;
       
       
   }
+1
ankitkumar734ac4 months ago
class Solution{
    static String decodedString(String s){
if(s == "")return "";
        String sol = new String();
        int repeat = 1;
        for(int i =0;i<s.length();++i)
        {
            if(Character.isDigit(s.charAt(i)))
            {
                String temp = "";
                int k = i;
                while(Character.isDigit(s.charAt(k)))
                {
                    temp+=s.charAt(k);
                    k++;
                }
                repeat = Integer.parseInt(temp);
                i = k-1;
            }
            else if(s.charAt(i) =='[')
            {
                Stack<Character> st = new Stack<>();
                st.push('[');
                int k = i+1;
                while(!st.isEmpty())
                {
                    if(s.charAt(k) == ']')
                    {
                        st.pop();
                        k++;
                    }
                    else if(s.charAt(k) =='[')
                    {
                        st.push('[');
                        k++;
                    }
                    else k++;
                }
                String inside_bracket = decodedString(s.substring(i+1,k-1));
                i = k-1;
                for(int j =0;j<repeat;++j)
                {
                    sol+=inside_bracket;
                }
            }
            
            else
            {
                sol+=s.charAt(i);
            }
        }
        return sol;
    }
}
+1
mmodi01014 months ago
string decodedString(string s){
        // code here
        string num = "";
        string ans="";
        int n;
        string temp="";
        string temp2="";
        stack<char> st;
        int p = 0;
        
        while(p<s.size())
        {    if(s[p]==']')
             {  while(st.top() != '[')
                {
                    temp=st.top()+temp;
                    st.pop();
                }
                 st.pop();
              while(isdigit(st.top()))
                {    num=st.top()+num;
                     st.pop();
                     if(st.empty()){
                         break;
                     }
                }
                n=stoi(num);
                for(int i=1;i<=n;i++)
                {   temp2=temp2+temp;
                }
                if(st.empty())
                {   ans=temp2;
                    break;
                }
                for(int i=0;i<temp2.size();i++)
                {    st.push(temp2[i]);
                }
                
                temp="";
                temp2="";
                num="";
            }
            else
            {    st.push(s[p]);
            }
            p++;
        }
        return ans;
    }
 
Time : 0.0s
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.