Files
illustrated-algorithm/longest-valid-parentheses/index.html
T
2026-08-24 04:35:13 +00:00

219 lines
8.7 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>090. 最长有效括号 – 图解</title>
<link rel="stylesheet" href="../shared/style.css">
<style>
/* page-specific overrides */
.vis-area { min-height: 120px; padding: 16px 0; }
.code-section { margin-top: 16px; }
</style>
</head>
<body>
<div class="container">
<h1>🔴 090. 最长有效括号 <span class="badge hard">困难</span></h1>
<p class="subtitle">分类:动态规划 | LeetCode Hot 100</p>
<!-- 控制面板 -->
<div class="controls" id="controls">
<label for="inputArea">输入:</label>
<input type="text" id="inputArea" placeholder="默认示例,可自定义">
<button id="applyBtn" class="primary">生成图解</button>
<select id="exampleSelect"></select>
<span style="flex:1"></span>
<button id="prevBtn">◀ 上一步</button>
<button id="nextBtn">下一步 ▶</button>
<button id="jumpBtn">⏭ 跳到结果</button>
<button id="autoBtn">自动播放</button>
<button id="resetBtn">重置</button>
</div>
<!-- 步骤流水线 -->
<div class="pipeline" id="pipeline"></div>
<!-- 提示条 -->
<div class="hint info" id="hintBox">
<span id="stepInfo"></span><br>
<span id="hintText"></span>
</div>
<!-- 可视化面板 -->
<div class="panels">
<div class="panel" id="mainPanel">
<h3>📊 可视化</h3>
<div class="vis-area" id="vizArea">点击「生成图解」开始</div>
</div>
<div class="panel-grid">
<div class="panel" id="detailPanel">
<h3>📝 当前步骤详情</h3>
<div id="detailContent">等待开始...</div>
</div>
<div class="panel" id="resultPanel">
<h3>✅ 结果</h3>
<div id="resultContent">等待完成...</div>
</div>
</div>
</div>
<!-- 代码 -->
<div class="panel code-section">
<h3>💻 参考代码(Python)</h3>
<div id="codeArea"></div>
</div>
<footer>Powered by QwenPaw · 图解算法 · LeetCode Hot 100</footer>
</div>
<script src="../shared/algo-viz.js"></script>
<script>
"use strict";
(function() {
// ========== Algorithm Logic ==========
const examples = [
{input: '(()', label: '示例1: "(()"'},
{input: ')()())', label: '示例2: ")()())"'},
{input: '', label: '示例3: ""'},
];
let s, steps, stepCtrl;
function buildSteps(str) {
s = str; steps = [];
if (str.length === 0) {
steps.push({stage:'done', msg:'空字符串,结果为 0', dp:[], stack:[-1], maxLen:0, current:-1, matched:-1});
return;
}
const n = str.length;
const dp = new Array(n).fill(0);
const stackArr = [-1];
let maxLen = 0;
steps.push({stage:'init', msg:'用栈方法:栈中保存索引,初始压入 -1 作为基线', dp:[...dp], stack:[-1], maxLen:0, current:-1, matched:-1});
for (let i = 0; i < n; i++) {
steps.push({stage:'check', msg:`处理 s[${i}]='${str[i]}'`, dp:[...dp], stack:[...stackArr], maxLen, current:i, matched:-1});
if (str[i] === '(') {
stackArr.push(i);
steps.push({stage:'push', msg:`遇到 '(',压入索引 ${i}`, dp:[...dp], stack:[...stackArr], maxLen, current:i, matched:-1});
} else {
if (stackArr.length > 1) {
stackArr.pop();
const start = stackArr[stackArr.length - 1];
const len = i - start;
maxLen = Math.max(maxLen, len);
dp[i] = len;
steps.push({stage:'pop', msg:`遇到 ')',弹出栈顶,栈顶=${start},有效长度=${i}-${start}=${len}`, dp:[...dp], stack:[...stackArr], maxLen, current:i, matched:start});
} else {
stackArr.length = 0;
stackArr.push(i);
steps.push({stage:'reset', msg:`遇到 ')' 但栈空(无匹配),重置基线为 ${i}`, dp:[...dp], stack:[...stackArr], maxLen, current:i, matched:-1});
}
}
}
steps.push({stage:'done', msg:`最长有效括号子串长度 = ${maxLen}`, dp:[...dp], stack:[...stackArr], maxLen, current:-1, matched:-1});
}
function render(step) {
const st = steps[step];
if (!st.dp || st.dp.length === 0) {
$('vizArea').innerHTML = '<div class="formula-box">空字符串,结果为 0</div>';
$('detailContent').innerHTML = '<div class="calc-block">' + st.msg + '</div>';
$('resultContent').innerHTML = '<div class="final-answer">最长有效括号长度 = <b>0</b></div>';
$('hintText').textContent = st.msg;
$('pipeline').innerHTML = '<span class="pipe-step active">完成</span>';
return;
}
let viz = '<div style="margin-top:8px;"><b>字符串:</b></div>';
viz += '<div style="display:flex;gap:3px;margin:8px 0;">';
for (let i = 0; i < s.length; i++) {
let cls = 'default';
if (i === st.current) cls = 'orange';
else if (st.dp[i] > 0) cls = 'green';
else if (i === st.matched) cls = 'blue';
viz += `<span class="chip ${cls}" style="min-width:28px;font-size:14px;">${s[i]}</span>`;
}
viz += '</div>';
viz += '<div style="display:flex;gap:3px;margin-top:-4px;">';
for (let i = 0; i < s.length; i++) {
viz += `<span style="min-width:28px;text-align:center;font-size:10px;color:var(--text-muted);">${i}</span>`;
}
viz += '</div>';
viz += '<div style="margin-top:8px;"><b>dp 值(以各位置结尾的有效长度):</b></div>';
viz += '<div style="display:flex;gap:3px;margin:4px 0;">';
for (let i = 0; i < s.length; i++) {
let cls = st.dp[i] > 0 ? 'green' : 'default';
if (i === st.current) cls = 'orange';
viz += `<span class="chip ${cls}" style="min-width:28px;font-size:12px;height:28px;">${st.dp[i]}</span>`;
}
viz += '</div>';
if (st.stack) {
viz += '<div style="margin-top:8px;"><b>栈:</b></div>';
viz += '<div style="display:flex;gap:3px;flex-wrap:wrap;margin:4px 0;">';
st.stack.forEach((v, idx) => {
const cls = idx === st.stack.length - 1 ? 'blue' : 'default';
viz += `<span class="chip ${cls}" style="min-width:28px;font-size:12px;height:28px;">${v}</span>`;
});
viz += '</div>';
}
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + st.msg + '</div>';
if (st.maxLen > 0) {
$('detailContent').innerHTML += `<div class="current-answer">当前最长有效长度:<b>${st.maxLen}</b></div>`;
}
if (st.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">最长有效括号子串长度 = <b>${st.maxLen}</b></div>`;
}
$('hintText').textContent = st.msg;
const stages = ['init→初始化','check→检查','push→入栈','pop→匹配','reset→重置','done→完成'];
$('pipeline').innerHTML = stages.map(st2 => {
const [k,l] = st2.split('→');
return `<span class="pipe-step ${st.stage===k?'active':''}">${l}</span>`;
}).join('<i>→</i>');
}
function init() {
const sel = $('exampleSelect');
examples.forEach((e,i) => { sel.innerHTML += `<option value="${i}">${e.label}</option>`; });
$('inputArea').value = '"(()"';
buildSteps(examples[0].input);
stepCtrl = new StepController({onStep: render});
stepCtrl.setSteps(steps.map((_,i)=>i));
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
stepCtrl.onStep = (idx) => { render(idx); $('stepInfo').textContent = `步骤 ${idx+1} / ${steps.length}`; };
$('applyBtn').onclick = () => {
const m = $('inputArea').value.match(/"([^"]+)"/);
if (!m) { alert('格式: "(()"'); return; }
buildSteps(m[1]);
stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length;
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
$('inputArea').value = `"${e.input}"`;
buildSteps(e.input); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
};
$('prevBtn').onclick = () => stepCtrl.prev();
$('nextBtn').onclick = () => stepCtrl.next();
$('jumpBtn').onclick = () => stepCtrl.jumpToEnd();
$('autoBtn').onclick = () => { const on = stepCtrl.toggleAuto(); $('autoBtn').textContent = on ? '暂停' : '自动播放'; };
$('resetBtn').onclick = () => { stepCtrl.reset(); $('autoBtn').textContent = '自动播放'; };
}
init();
$('codeArea').innerHTML = renderCode(`def longestValidParentheses(s):
stack = [-1]
max_len = 0
for i, c in enumerate(s):
if c == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_len`, {lang:'Python'});
})();
</script>
</body>
</html>