LeetCode 75

Decode String

Problem
LC 394
Topic
Stack
File
official75_LC394DecodeString.java
Path
pkg5leetcode/official75/official75_LC394DecodeString.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC394DecodeString.java
Approach
Stack push current string and repeat count on '['.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC394DecodeString.java
1package pkg5leetcode.official75;2 3/*4 * Decode String | LC 3945 * APPROACH: Stack push current string and repeat count on '['.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class official75_LC394DecodeString {11    static String decodeString(String s) {12        Deque<StringBuilder> strSt = new ArrayDeque<>();13        Deque<Integer> numSt = new ArrayDeque<>();14        StringBuilder cur = new StringBuilder();15        int k = 0;16        for (char c : s.toCharArray()) {17            if (Character.isDigit(c)) k = k * 10 + (c - '0');18            else if (c == '[') {19                numSt.addLast(k);20                strSt.addLast(cur);21                cur = new StringBuilder();22                k = 0;23            } else if (c == ']') {24                StringBuilder prev = strSt.removeLast();25                int rep = numSt.removeLast();26                for (int i = 0; i < rep; i++) prev.append(cur);27                cur = prev;28            } else cur.append(c);29        }30        return cur.toString();31    }32 33    public static void main(String[] args) {34        check("aaabcbc".equals(decodeString("3[a]2[bc]")), "case1");35        check("accaccacc".equals(decodeString("3[a2[c]]")), "case2");36        System.out.println("all tests passed");37    }38 39    static void check(boolean cond, String name) {40        if (!cond) throw new AssertionError("FAILED: " + name);41        System.out.println("  PASS " + name);42    }43}