Data Structure & Algorithms
  • 🖌️Unlocking the Power of Algorithms with C#
  • Data Structure
    • Data Structure
    • Big O
    • Array
    • Linked Lists
    • Stacks
    • Queues
    • Hash Tables
    • Trees
    • Graphs
    • Heap Sort
    • ParkingLot Algorithm
    • LRU cache
    • Priority Queue
  • Algorithms
    • Algorithm
    • Recursion
    • Sorting
    • Searching
    • Dynamic Programming
  • Problems
    • Array
      • Two Sum
      • Two Sum II - Input Array Is Sorted
      • Contains Duplicate
      • Maximum Subarray
      • House Robber
      • Move Zeroes
      • Rotate Array
      • Plus One
      • Find number of subarrays with even length
      • Find number of subarrays with even sum
      • Find Missing Element
      • Reduce Array Size to The Half
      • Remove Duplicates
      • Merge Sorted Arrays
      • Arrays Intersection
      • 3Sum
      • Trapping Rain Water
      • Maximum sum of a subarray
      • Longest Subarray
      • Subarray Sum Equals K
      • Container With Most Water
      • Missing Number
      • Roman to Integer
      • First Missing Positive
      • Unique Integers That Sum Up To 0
      • Integer to Roman
      • Flatten
    • String
      • Check if two strings are permutation of each other
      • String Compression
      • Palindrome Permutation
      • Determine if a string has all Unique Characters
      • One Away
      • Longest Substring Without Repeating Characters
      • Valid Palindrome
      • Valid Palindrome II
      • Backspace String Compare
      • First Unique Character in a String
      • Is Subsequence
      • URLify a given string
      • String has same characters at same position
      • Number of Ways to Split a String
      • Check whether two Strings are anagram of each other
      • Print last `n` lines of a big file or big string.
      • Multiply Strings
    • Matrix
      • Search a 2D Matrix
      • Search a 2D Matrix II
      • Rotate Matrix
      • Spiral Matrix
      • Set Matrix Zeroes
    • Bit Manipulation
      • Sum of Two Integers
      • Reverse Number
      • Reverse Number II
      • Binary Bits Count
      • Binary Bits Count II
    • Stack
      • Valid Parentheses
      • Balance or not expression
      • Decode String
    • Tree
      • Binary Tree Inorder Traversal
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Return All Root-To-Leaf Paths
      • Binary Tree Height-Balanced
      • Valid Binary Search Tree
      • Binary Tree Sum of all left leaves.
    • Linked List
      • Linked List Delete Middle Node
      • Merge Sorted Linked List
      • Reverse Linked List
      • Remove Duplicates from Sorted List
      • Remove Duplicates from Unsorted List
      • Linked List Cycle
    • Graph
      • The Number Of Islands
      • Number of Closed Islands
      • Max Area of Island
      • Rotting Oranges
      • Number of Provinces
      • Course Schedule
      • Surrounded Regions
      • Snakes and Ladders
      • Widest Path Without Trees
      • Knight Probability in Chessboard
      • Possible moves of knight
      • Check Knight Tour Configuration
      • Steps by Knight
      • Network Delay Time
    • Greedy
      • Best Time to Buy and Sell Stock
      • Best Time to Buy and Sell Stock II
      • Smallest Subset Array
      • Jump Game
    • Backtracking
      • Towers of Hanoi
      • Subsets
      • Combination Sum
      • Sudoku Solver
      • Word Search
    • Heap
      • Kth Largest Element in an Array
      • Top K Frequent Elements
    • Sorting
      • Order Colors String
    • Recursion
      • Number To Text
      • Divide Number
Powered by GitBook
On this page
  1. Problems
  2. Stack

Decode String

String, Stack Approach

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].

Solutions

This problem is a classic example of a problem that can be solved using a stack data structure. Here’s a step-by-step approach:

  1. Initialize an empty stack: We’ll use this to keep track of the strings we need to repeat and the number of times we need to repeat them.

  2. Iterate over the input string: We’ll look at each character one by one.

  3. When we encounter a number, we know that it represents the number of times the following string should be repeated. We push this number onto our stack.

  4. When we encounter an opening bracket ‘[’, this indicates the start of the string to be repeated. We push this onto our stack to mark the beginning of this string.

  5. When we encounter a letter, we add it to the top of our stack (which should always be a string).

  6. When we encounter a closing bracket ‘]’, this indicates the end of the current repeated string. We pop elements from our stack until we reach an opening bracket, concatenating these letters together to form our repeated string. We then pop the opening bracket and the number preceding it from our stack, and add the repeated string to our stack that many times.

  7. At the end of our input string, our stack should contain one element: the decoded string. We return this as our result.

This approach works because the stack allows us to handle the nested structure of the input string, ensuring that we always repeat the correct strings the correct number of times. It’s a bit like peeling an onion: we handle the outermost layer first, then the next layer, and so on, until we reach the core.

Steps


public class Solution {
public string DecodeString(string s) {
    var stack = new Stack<string>();
    stack.Push("");
    
    int num = 0;
    foreach (char c in s) {
        if (char.IsDigit(c)) {
            num = num * 10 + (c - '0');
        } else if (c == '[') {
            stack.Push(num.ToString());
            stack.Push("");
            num = 0;
        } else if (c == ']') {
            string str = stack.Pop();
            int count = Int32.Parse(stack.Pop());
            var sb = new StringBuilder(stack.Pop());
            for (int i = 0; i < count; i++) {
                sb.Append(str);
            }
            stack.Push(sb.ToString());
        } else {
            stack.Push(stack.Pop() + c);
        }
    }
    return stack.Pop();
 }
}

Complexity

  • Time Complexity: O(1)

  • Auxiliary Space: O(1)

PreviousBalance or not expressionNextTree

Last updated 1 year ago