Day 49 of 100 Days LeetCode Challenge
Question 26 of 75 - LeetCode Weekly Challenge

LeetCode Challenge #394. Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].

The test cases are generated so that the length of the output will never exceed 105.

 

Example 1:

Input: s = "3[a]2[bc]"
Output: "aaabcbc"

Example 2:

Input: s = "3[a2[c]]"
Output: "accaccacc"

Example 3:

Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"

 

Constraints:

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].
C++ Video Solution
Java Video Solution
Java Solution
				
					class Solution {
    public String decodeString(String s) {
        Stack<Integer> numberStack = new Stack<>();
        Stack<String> mainStack = new Stack<>();

        for(int i=0;i<s.length();i++){
            char ch = s.charAt(i);

            if(ch>='0' && ch<='9'){ // identifing it is a number 
                int num = 0 ;

                while(i<s.length() && s.charAt(i)>='0' && s.charAt(i)<='9'){
                    num = num * 10  + (int)(s.charAt(i)-'0');
                    i++;
                }
                i--; // to maintain the loop variable
                numberStack.push(num);
            }else if ( ch != ']'){
                mainStack.push(ch + "");
            }else { // condition for ']'
                String str = "";
                while(!mainStack.peek().equals("[")){
                    str = mainStack.pop() + str ;
                }
                mainStack.pop();
                int repetationNumber = numberStack.pop();

                StringBuilder sb = new StringBuilder("") ;

                while(repetationNumber>0){
                    sb.append(str);
                    repetationNumber--;
                }

                 mainStack.push(sb.toString());
            }
        }

        StringBuilder ans = new StringBuilder("");

        while(mainStack.size()>0){
            ans.insert(0,mainStack.pop());
        }
        return ans.toString();
    }
}
				
			
C++ Solution
				
					class Solution {
public:
    string decodeString(string s) {

        stack<pair<int,string>> helper;
        string ans;
        int i=0;

        while(i<s.size())
        {
            if(s[i]>='0' and s[i]<='9')
            {
                int j=i;
                while(s[i]>='0' and s[i]<='9')
                {
                    i++;
                }
                int num= stoi(s.substr(j, i-j));
                helper.push({num,""});
            }
            else if(s[i]>='a' and s[i]<='z')
            {
                int j=i;
                while(s[i]>='a' and s[i]<='z') i++;

                string curr= s.substr(j,i-j);
                if(helper.empty()) ans+=curr;
                else helper.top().second+=curr;
            }
            else if(s[i]==']')
            {
                int itr=helper.top().first;
                string curr= "";

                while(itr--)curr+=helper.top().second;
                helper.pop();

                if(helper.empty())
                ans+=curr;
                else
                helper.top().second+=curr;

                i++;
            }
            else i++;
        }
        return ans;
    }
};
				
			
Code Explanation

In this program, we have to decode a string encoded with a specific pattern that involves repeating substrings. 

  1. We will initialise a stack of pairs named ‘helper’, and each pair consisting of an integer ‘int’ representing the number of repetitions and a string ‘string’, representing the decoded substring. 
  2. And another string, ‘ans’  is initialised to store the final decoded result.
  3. The algorithm iterates to each character of the input string and three cases are considered :
    • if the current character is a digit between 0 and 9 then we will increment i (‘i++’)
      For storing the element in the stack so for this, we will push a pair {‘num, “”” } 
  1. Now, for handling the alphabets –
    If the current character is a lowercase letter ( between ‘a’ and ‘z’ ), then the same condition is used as earlier, increment i (‘i++’). A substring ‘curr=s’ is used from ‘i’ to ‘j’ ( the substring is appended directly to the final result ). 
  1. Now we’ll check if the string is empty till now, that means we have not got any number and that means we do not have to repeat this string And that means we have received our answer.
  1. NOTE, we do not have to handle open brackets again here, because we already handled them in the above alphabets but we do have to handle ‘closing brackets’ if ‘]’ is encountered then we will process the top of the stack, and the repeated substring is updated accordingly.

Happy Coding with edSlash