223 lines
9.3 KiB
HTML
223 lines
9.3 KiB
HTML
|
|
<!DOCTYPE html>
|
|||
|
|
<html lang="zh-Hans">
|
|||
|
|
<head>
|
|||
|
|
<meta charset="UTF-8">
|
|||
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|||
|
|
<title>012. 最小覆盖子串 – 图解</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>🔴 012. 最小覆盖子串 <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: "ADOBECODEBANC", t: "ABC", label: '示例1: s="ADOBECODEBANC", t="ABC"'},
|
|||
|
|
{input: "a", t: "a", label: '示例2: s="a", t="a"'},
|
|||
|
|
{input: "a", t: "aa", label: '示例3: s="a", t="aa"'},
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
let s, t, steps, stepCtrl;
|
|||
|
|
|
|||
|
|
function buildSteps(str, target) {
|
|||
|
|
s = str; t = target; steps = [];
|
|||
|
|
const need = {};
|
|||
|
|
for (const ch of target) need[ch] = (need[ch] || 0) + 1;
|
|||
|
|
const needKeys = Object.keys(need);
|
|||
|
|
const totalNeed = needKeys.length;
|
|||
|
|
let have = 0;
|
|||
|
|
const window = {};
|
|||
|
|
let left = 0;
|
|||
|
|
let minLen = Infinity, minLeft = -1;
|
|||
|
|
|
|||
|
|
steps.push({stage:'init', msg:`初始化:need={${needKeys.map(k=>k+':'+need[k]).join(', ')}},需要满足 ${totalNeed} 种字符`, left:0, right:-1, window:{}, have:0, need:{...need}, minLen, minLeft, totalNeed});
|
|||
|
|
|
|||
|
|
for (let right = 0; right < str.length; right++) {
|
|||
|
|
const ch = str[right];
|
|||
|
|
window[ch] = (window[ch] || 0) + 1;
|
|||
|
|
if (need[ch] && window[ch] === need[ch]) have++;
|
|||
|
|
steps.push({stage:'expand', msg:`right=${right},加入 '${ch}',window['${ch}']=${window[ch]},have=${have}/${totalNeed}`, left, right, window:{...window}, have, need:{...need}, minLen, minLeft, totalNeed});
|
|||
|
|
|
|||
|
|
while (have === totalNeed) {
|
|||
|
|
const curLen = right - left + 1;
|
|||
|
|
if (curLen < minLen) {
|
|||
|
|
minLen = curLen; minLeft = left;
|
|||
|
|
steps.push({stage:'update', msg:`找到有效窗口 [${left},${right}],长度=${curLen},更新最小窗口`, left, right, window:{...window}, have, need:{...need}, minLen, minLeft, totalNeed});
|
|||
|
|
}
|
|||
|
|
const leftCh = str[left];
|
|||
|
|
window[leftCh]--;
|
|||
|
|
if (need[leftCh] && window[leftCh] < need[leftCh]) have--;
|
|||
|
|
left++;
|
|||
|
|
steps.push({stage:'shrink', msg:`收缩左边 '${leftCh}',left=${left},have=${have}/${totalNeed}`, left, right, window:{...window}, have, need:{...need}, minLen, minLeft, totalNeed});
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
if (minLeft === -1) {
|
|||
|
|
steps.push({stage:'done', msg:'遍历完毕,未找到覆盖子串', left:0, right:s.length-1, window:{}, have:0, need:{...need}, minLen:0, minLeft:-1, totalNeed});
|
|||
|
|
} else {
|
|||
|
|
steps.push({stage:'done', msg:`最小覆盖子串: "${s.slice(minLeft, minLeft+minLen)}",长度=${minLen}`, left:minLeft, right:minLeft+minLen-1, window:{}, have:0, need:{...need}, minLen, minLeft, totalNeed});
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function render(step) {
|
|||
|
|
const s_ = steps[step];
|
|||
|
|
const hl = {};
|
|||
|
|
if (s_.left >= 0 && s_.right >= 0) {
|
|||
|
|
for (let i = s_.left; i <= Math.min(s_.right, s.length - 1); i++) hl[i] = 'blue';
|
|||
|
|
}
|
|||
|
|
if (s_.stage === 'update' || s_.stage === 'done') {
|
|||
|
|
if (s_.minLeft >= 0) {
|
|||
|
|
for (let i = s_.minLeft; i < s_.minLeft + s_.minLen && i < s.length; i++) hl[i] = 'green';
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
let viz = '<div style="margin-bottom:6px;"><b>s = </b></div>';
|
|||
|
|
viz += renderArray(s.split(''), {highlights: hl, pointers: s_.left >= 0 && s_.right >= 0 ? {L: s_.left, R: Math.min(s_.right, s.length-1)} : {}});
|
|||
|
|
viz += '<div style="margin:10px 0 6px;"><b>t = </b></div>';
|
|||
|
|
viz += renderArray(t.split(''), {highlights: {}});
|
|||
|
|
|
|||
|
|
const allKeys = [...new Set([...Object.keys(s_.need), ...Object.keys(s_.window)])].sort();
|
|||
|
|
viz += '<div class="table-wrap" style="margin-top:12px;"><table><tr><th>字符</th><th>需要</th><th>窗口有</th><th>满足?</th></tr>';
|
|||
|
|
allKeys.forEach(k_ => {
|
|||
|
|
const nv = s_.need[k_] || 0;
|
|||
|
|
const wv = s_.window[k_] || 0;
|
|||
|
|
const satisfied = wv >= nv;
|
|||
|
|
viz += `<tr><td><code>'${k_}'</code></td><td>${nv}</td><td>${wv}</td><td style="color:${satisfied?'var(--green)':'var(--red)'};font-weight:700;">${satisfied?'✓':'✗'}</td></tr>`;
|
|||
|
|
});
|
|||
|
|
viz += '</table></div>';
|
|||
|
|
viz += `<div style="margin-top:6px;">have=${s_.have} / need=${s_.totalNeed} 种字符满足</div>`;
|
|||
|
|
if (s_.minLen < Infinity && s_.minLen > 0) {
|
|||
|
|
viz += `<div style="margin-top:4px;color:var(--green-dark);font-weight:600;">最小窗口: "${s.slice(s_.minLeft, s_.minLeft + s_.minLen)}" 长度=${s_.minLen}</div>`;
|
|||
|
|
}
|
|||
|
|
$('vizArea').innerHTML = viz;
|
|||
|
|
$('detailContent').innerHTML = '<div class="calc-block">' + s_.msg + '</div>';
|
|||
|
|
|
|||
|
|
if (s_.stage === 'done') {
|
|||
|
|
if (s_.minLeft === -1) {
|
|||
|
|
$('resultContent').innerHTML = '<div class="final-answer" style="border-color:#f87171;background:#fef2f2;">未找到覆盖子串,返回空串</div>';
|
|||
|
|
} else {
|
|||
|
|
$('resultContent').innerHTML = `<div class="final-answer">最小覆盖子串 = <b>"${s.slice(s_.minLeft, s_.minLeft + s_.minLen)}"</b><br>长度 = ${s_.minLen}</div>`;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
$('hintText').textContent = s_.msg;
|
|||
|
|
const stages = ['init→初始化','expand→扩展','update→更新','shrink→收缩','done→完成'];
|
|||
|
|
$('pipeline').innerHTML = stages.map(st => {
|
|||
|
|
const [k_,l] = st.split('→');
|
|||
|
|
return `<span class="pipe-step ${s_.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 = 's="ADOBECODEBANC", t="ABC"';
|
|||
|
|
buildSteps(examples[0].input, examples[0].t);
|
|||
|
|
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(/s="([^"]+)".*t="([^"]+)"/);
|
|||
|
|
if (!m) { alert('格式: s="ADOBECODEBANC", t="ABC"'); return; }
|
|||
|
|
buildSteps(m[1], m[2]); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
|
|||
|
|
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
|
|||
|
|
};
|
|||
|
|
$('exampleSelect').onchange = () => {
|
|||
|
|
const e = examples[parseInt($('exampleSelect').value)];
|
|||
|
|
$('inputArea').value = `s="${e.input}", t="${e.t}"`;
|
|||
|
|
buildSteps(e.input, e.t); 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 minWindow(s, t):
|
|||
|
|
from collections import Counter
|
|||
|
|
need = Counter(t)
|
|||
|
|
window = {}
|
|||
|
|
have, need_cnt = 0, len(need)
|
|||
|
|
left = 0
|
|||
|
|
min_len = float('inf')
|
|||
|
|
min_left = -1
|
|||
|
|
for right, ch in enumerate(s):
|
|||
|
|
window[ch] = window.get(ch, 0) + 1
|
|||
|
|
if ch in need and window[ch] == need[ch]:
|
|||
|
|
have += 1
|
|||
|
|
while have == need_cnt:
|
|||
|
|
if right - left + 1 < min_len:
|
|||
|
|
min_len = right - left + 1
|
|||
|
|
min_left = left
|
|||
|
|
left_ch = s[left]
|
|||
|
|
window[left_ch] -= 1
|
|||
|
|
if left_ch in need and window[left_ch] < need[left_ch]:
|
|||
|
|
have -= 1
|
|||
|
|
left += 1
|
|||
|
|
return "" if min_left == -1 else s[min_left:min_left+min_len]`, {lang:'Python'});
|
|||
|
|
|
|||
|
|
})();
|
|||
|
|
</script>
|
|||
|
|
</body>
|
|||
|
|
</html>
|