Files
illustrated-algorithm/find-all-anagrams-in-a-string/index.html
T
2026-08-24 04:35:13 +00:00

209 lines
8.4 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>009. 找到字符串中所有字母异位词 – 图解</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>🟡 009. 找到字符串中所有字母异位词 <span class="badge medium">中等</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: "cbaebabacd", p: "abc", label: '示例1: s="cbaebabacd", p="abc"'},
{input: "abab", p: "ab", label: '示例2: s="abab", p="ab"'},
];
let s, p, steps, stepCtrl;
function buildSteps(str, pattern) {
s = str; p = pattern; steps = [];
const pLen = pattern.length;
const pFreq = {};
for (const ch of pattern) pFreq[ch] = (pFreq[ch] || 0) + 1;
const sFreq = {};
let left = 0;
const result = [];
steps.push({stage:'init', msg:`初始化:固定窗口大小=${pLen},统计 p 的频率`, left:0, right:-1, sFreq:{}, pFreq:{...pFreq}, result:[], matchCount:0});
for (let right = 0; right < str.length; right++) {
const ch = str[right];
sFreq[ch] = (sFreq[ch] || 0) + 1;
let matchCount = 0;
for (const k in pFreq) { if (sFreq[k] === pFreq[k]) matchCount++; }
const totalKeys = Object.keys(pFreq).length;
steps.push({stage:'expand', msg:`right=${right},加入 '${ch}',窗口 [${left},${right}]`, left, right, sFreq:{...sFreq}, pFreq:{...pFreq}, result:[...result], matchCount, totalKeys});
if (right - left + 1 > pLen) {
const removed = str[left];
sFreq[removed]--;
if (sFreq[removed] === 0) delete sFreq[removed];
left++;
matchCount = 0;
for (const k in pFreq) { if (sFreq[k] === pFreq[k]) matchCount++; }
steps.push({stage:'shrink', msg:`窗口超出大小,移除左边 '${removed}',left=${left}`, left, right, sFreq:{...sFreq}, pFreq:{...pFreq}, result:[...result], matchCount, totalKeys});
}
if (right - left + 1 === pLen) {
if (matchCount === totalKeys) {
result.push(left);
steps.push({stage:'found', msg:`窗口 [${left},${right}] 是异位词!记录起始位置 ${left}`, left, right, sFreq:{...sFreq}, pFreq:{...pFreq}, result:[...result], matchCount, totalKeys});
}
}
}
steps.push({stage:'done', msg:`遍历完毕,找到 ${result.length} 个异位词起始位置`, left:0, right:s.length-1, sFreq:{}, pFreq:{...pFreq}, result:[...result], matchCount:0, totalKeys:Object.keys(pFreq).length});
}
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 === 'found') {
for (let i = s_.left; i <= Math.min(s_.right, s.length - 1); i++) hl[i] = 'green';
}
let viz = '<div style="margin-bottom:6px;"><b>s = </b></div>';
viz += renderArray(s.split(''), {highlights: hl, pointers: {L: s_.left, R: s_.right >= 0 && s_.right < s.length ? s_.right : -1}});
viz += '<div style="margin:10px 0 6px;"><b>p = </b></div>';
viz += renderArray(p.split(''), {highlights: {}});
viz += '<div class="table-wrap" style="margin-top:12px;"><table><tr><th>字符</th><th>p 频率</th><th>窗口频率</th><th>匹配?</th></tr>';
const allKeys = [...new Set([...Object.keys(s_.pFreq), ...Object.keys(s_.sFreq)])].sort();
allKeys.forEach(k => {
const pv = s_.pFreq[k] || 0;
const sv = s_.sFreq[k] || 0;
const match = pv === sv;
viz += `<tr><td><code>'${k}'</code></td><td>${pv}</td><td>${sv}</td><td style="color:${match?'var(--green)':'var(--red)'};font-weight:700;">${match?'✓':'✗'}</td></tr>`;
});
viz += '</table></div>';
if (s_.matchCount !== undefined && s_.totalKeys) {
viz += `<div style="margin-top:6px;">匹配字符数: ${s_.matchCount} / ${s_.totalKeys}</div>`;
}
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s_.msg + '</div>';
if (s_.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">起始索引 = <b>[${s_.result}]</b><br>共找到 ${s_.result.length} 个异位词</div>`;
}
$('hintText').textContent = s_.msg;
const stages = ['init→初始化','expand→扩展','shrink→收缩','found→找到','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="cbaebabacd", p="abc"';
buildSteps(examples[0].input, examples[0].p);
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="([^"]+)".*p="([^"]+)"/);
if (!m) { alert('格式: s="cbaebabacd", p="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}", p="${e.p}"`;
buildSteps(e.input, e.p); 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 findAnagrams(s, p):
from collections import Counter
p_freq = Counter(p)
s_freq = Counter()
left = 0
result = []
for right in range(len(s)):
s_freq[s[right]] += 1
if right - left + 1 > len(p):
s_freq[s[left]] -= 1
if s_freq[s[left]] == 0:
del s_freq[s[left]]
left += 1
if right - left + 1 == len(p) and s_freq == p_freq:
result.append(left)
return result`, {lang:'Python'});
})();
</script>
</body>
</html>