LeetCode //C - 394. Decode String

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 1 0 5 10^5 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.
  • ll the integers in s are in the range [1, 300].

From: LeetCode

Link: 394. Decode String


Solution:

Ideas:
  1. Stack Implementation: Since the problem involves nested structures and the need to process the most recent open bracket first, a stack data structure is suitable. We'll use two stacks: one for characters and one for integers.

  2. Parsing the Input String: We iterate through the input string. When we encounter a digit, we calculate the whole number (as numbers can have more than one digit) and push it onto the integer stack. When we encounter a '[', we push a marker onto the character stack. For letters, we simply push them onto the character stack.

  3. Decoding: When we encounter a ']', it means we need to decode the string within the last '[' and ']' encountered. We pop characters from the character stack until we reach the marker, build the string, then multiply it according to the top value of the integer stack, and push the result back onto the character stack.

  4. Building the Result: After processing the entire input string, the character stack will contain the decoded string. We then pop all characters to build the final result.

  5. Memory Management: Since we need to return a dynamically allocated string, we need to ensure proper memory allocation and deallocation to avoid memory leaks.

Code:
c 复制代码
char* decodeString(char* s) {
    int numStack[30], numTop = -1;     // Stack for numbers
    char charStack[30000], *p = s;     // Stack for characters
    int charTop = -1, num = 0;

    while (*p) {
        if (isdigit(*p)) {             // If it's a digit, calculate the number
            num = num * 10 + (*p - '0');
        } else if (*p == '[') {
            numStack[++numTop] = num;  // Push the number onto the numStack
            charStack[++charTop] = '['; // Push a marker onto the charStack
            num = 0;                   // Reset the number for next use
        } else if (*p == ']') {
            int repeat = numStack[numTop--]; // Pop the top number for repetition
            char temp[30000], *tempPtr = temp;
            while (charStack[charTop] != '[') // Build the string to repeat
                *tempPtr++ = charStack[charTop--];
            charTop--;                       // Pop the '[' marker
            while (repeat-- > 0)             // Repeat the string
                for (char* k = tempPtr - 1; k >= temp; k--)
                    charStack[++charTop] = *k;
        } else {
            charStack[++charTop] = *p;      // Push the character onto the stack
        }
        p++;
    }
    
    charStack[++charTop] = '\0';            // Null-terminate the string
    char* result = (char*)malloc(charTop + 1);
    strcpy(result, charStack);              // Copy the stack content to result
    return result;
}
相关推荐
九年义务漏网鲨鱼32 分钟前
【大模型面经】千问系列专题面经
人工智能·深度学习·算法·大模型·强化学习
源码之家1 小时前
机器学习:基于大数据二手房房价预测与分析系统 可视化 线性回归预测算法 Django框架 链家网站 二手房 计算机毕业设计✅
大数据·算法·机器学习·数据分析·spark·线性回归·推荐算法
Lv Jianwei1 小时前
Longest Palindromic Substring最长回文子串-学习动态规划Dynamic Programming(DP)
算法
WWZZ20252 小时前
快速上手大模型:深度学习7(实践:卷积层)
人工智能·深度学习·算法·机器人·大模型·卷积神经网络·具身智能
l1t2 小时前
用SQL求解advent of code 2024年23题
数据库·sql·算法
10岁的博客2 小时前
二维差分算法高效解靶场问题
java·服务器·算法
轻微的风格艾丝凡2 小时前
锂电池 SOC 估计技术综述:成熟算法、新颖突破与车企应用实践
算法·汽车
Codeking__3 小时前
动态规划算法经典问题——01背包问题
算法·动态规划
R-G-B3 小时前
归并排序 (BM20 数组中的逆序对)
数据结构·算法·排序算法
少许极端3 小时前
算法奇妙屋(十二)-优先级队列(堆)
数据结构·算法·leetcode·优先级队列··图解算法