Decode String LeetCode Solution

Last updated on October 6th, 2024 at 08:36 pm

Here, We see Decode String LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Depth-First Search, Stack

Companies

Google, Yelp

Level of Question

Medium

Decode String LeetCode Solution

Decode String LeetCode Solution

Problem Statement

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”

1. Decode String LeetCode Solution C++

class Solution {
public:
    string decodeString(string s) {
        stack<char> st;
        for(int i = 0; i < s.size(); i++){
            if(s[i] != ']') {
                st.push(s[i]);
            }
            else{
                string curr_str = "";
                while(st.top() != '['){
                    curr_str = st.top() + curr_str ;
                    st.pop();
                }
                st.pop();
                string number = "";
                while(!st.empty() && isdigit(st.top())){
                    number = st.top() + number;
                    st.pop();
                }
                int k_time = stoi(number);
                
                while(k_time--){
                    for(int p = 0; p < curr_str.size() ; p++)
                        st.push(curr_str[p]);
                }
            }
        }
        s = "";
        while(!st.empty()){
            s = st.top() + s;
            st.pop();
        }
        return s;
    }
};

2. Decode String Solution Java

class Solution {
    public String decodeString(String s) {
            Stack<Character> stack = new Stack<>();
            for(char c : s.toCharArray())
            {
                if(c != ']') 
                    stack.push(c);
                else 
                {
                    StringBuilder sb = new StringBuilder();
                    while(!stack.isEmpty() && Character.isLetter(stack.peek()))
                        sb.insert(0, stack.pop());
                    String sub = sb.toString();
                    stack.pop();
                    sb = new StringBuilder();
                    while(!stack.isEmpty() && Character.isDigit(stack.peek()))
                        sb.insert(0, stack.pop());
                    int count = Integer.valueOf(sb.toString());
                    while(count > 0)
                    {
                        for(char ch : sub.toCharArray())  
                            stack.push(ch);
                        count--;
                    }
                }
            }
            StringBuilder retv = new StringBuilder();
            while(!stack.isEmpty())
                retv.insert(0, stack.pop());
            return retv.toString();
        }
}

3. Decode String Solution JavaScript

var decodeString = function(s) {
  const stack = [];
  for (const char of s) {
    if (char !== "]") { stack.push(char); continue; }
    let cur = stack.pop();
    let str = '';
    while (cur !== '[') {
      str = cur + str;
      cur = stack.pop();
    }
    let num = '';
    cur = stack.pop();
    while (!Number.isNaN(Number(cur))) {
      num = cur + num;
      cur = stack.pop();
    }
    stack.push(cur);
    stack.push(str.repeat(Number(num)));
  }
  return stack.join('');    
};

4. Decode String Solution Python

class Solution(object):
    def decodeString(self, s):
        stack = []; curNum = 0; curString = ''
        for c in s:
            if c == '[':
                stack.append(curString)
                stack.append(curNum)
                curString = ''
                curNum = 0
            elif c == ']':
                num = stack.pop()
                prevString = stack.pop()
                curString = prevString + num*curString
            elif c.isdigit():
                curNum = curNum*10 + int(c)
            else:
                curString += c
        return curString
Scroll to Top