İçeriğe atla
ΣDSA Patterns
Menü
Dil

Yığın ile Ayrıştırma

Rehber 5 / 6 · Yol 5 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Decode String

Problem (restated)

Encoded string like 3[a2[c]]accaccacc. Digits mean repeat count; brackets nest.

Intuition

Two stacks (or one stack of frames): counts and string builders. On ] pop and repeat.

Approaches

Stack parse

Tested only
Time O(n · output)Space O(output)

Idea. On digit accumulate k; on [ push frame; on letter append; on ] repeat and merge.

Walkthrough. 3[a]2[bc] → aaabcbc; 3[a2[c]] → accaccacc.

Trade-offs. Recursive descent is fine; stack mirrors call frames.

Solution
export function decodeString(s: string): string {
  const countSt: number[] = [];
  const strSt: string[] = [];
  let cur = "";
  let k = 0;
  for (const ch of s) {
    if (ch >= "0" && ch <= "9") k = k * 10 + (ch.charCodeAt(0) - 48);
    else if (ch === "[") {
      countSt.push(k);
      strSt.push(cur);
      cur = "";
      k = 0;
    } else if (ch === "]") {
      const times = countSt.pop()!;
      const prev = strSt.pop()!;
      cur = prev + cur.repeat(times);
    } else cur += ch;
  }
  return cur;
}
export function decodeString(s: string): string {
  const countSt: number[] = [];
  const strSt: string[] = [];
  let cur = "";
  let k = 0;
  for (const ch of s) {
    if (ch >= "0" && ch <= "9") k = k * 10 + (ch.charCodeAt(0) - 48);
    else if (ch === "[") {
      countSt.push(k);
      strSt.push(cur);
      cur = "";
      k = 0;
    } else if (ch === "]") {
      const times = countSt.pop()!;
      const prev = strSt.pop()!;
      cur = prev + cur.repeat(times);
    } else cur += ch;
  }
  return cur;
}

Template connection

Stack-parsing nested structures.

Reflection