Files

197 lines
8.1 KiB
HTML
Raw Permalink Normal View History

<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>086. 单词拆分 – 图解</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>🟡 086. 单词拆分 <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: 'leetcode', dict: ['leet','code'], label: '示例1: "leetcode", ["leet","code"]'},
{input: 'applepenapple', dict: ['apple','pen'], label: '示例2: "applepenapple", ["apple","pen"]'},
{input: 'catsandog', dict: ['cats','dog','sand','and','cat'], label: '示例3: "catsandog"'},
];
let s, wordDict, steps, stepCtrl;
function buildSteps(str, dict) {
s = str; wordDict = dict; steps = [];
const n = str.length;
const dp = new Array(n + 1).fill(false);
dp[0] = true;
steps.push({stage:'init', msg:'dp[0]=true(空串可分割)', dp:[...dp], i:-1, j:-1, matched:false, matchWord:''});
for (let i = 1; i <= n; i++) {
steps.push({stage:'checkI', msg:`检查 dp[${i}]:能否将 s[0:${i}]="${s.slice(0,i)}" 分割`, dp:[...dp], i, j:-1, matched:false, matchWord:''});
for (let j = 0; j < i; j++) {
const sub = s.slice(j, i);
const inDict = dp[j] && dict.includes(sub);
if (dp[j]) {
steps.push({stage:'tryJ', msg:`dp[${j}]=true,检查 s[${j}:${i}]="${sub}" ${inDict?'在字典中 ✅':'不在字典中 ❌'}`, dp:[...dp], i, j, matched:inDict, matchWord:sub});
if (inDict) {
dp[i] = true;
steps.push({stage:'found', msg:`dp[${j}]=true 且 "${sub}" 在字典中 → dp[${i}]=true`, dp:[...dp], i, j, matched:true, matchWord:sub});
break;
}
}
}
if (!dp[i]) {
steps.push({stage:'fail', msg:`dp[${i}]=false(无法分割 s[0:${i}])`, dp:[...dp], i, j:-1, matched:false, matchWord:''});
}
}
steps.push({stage:'done', msg:dp[n]?`"${s}" 可以被分割`:`"${s}" 无法被分割`, dp:[...dp], i:n, j:-1, matched:dp[n], matchWord:''});
}
function render(step) {
const st = steps[step];
let viz = '<div style="margin-top:8px;"><b>字符串:</b></div>';
viz += '<div style="display:flex;gap:2px;margin:8px 0;">';
for (let i = 0; i < s.length; i++) {
const inRange = st.j >= 0 && i >= st.j && i < st.i;
const cls = inRange ? (st.matched ? 'green' : 'orange') : 'default';
viz += `<span class="chip ${cls}" style="min-width:28px;font-size:14px;">${s[i]}</span>`;
}
viz += '</div>';
viz += '<div style="display:flex;gap:2px;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;flex-wrap:wrap;margin:4px 0;">';
for (let i = 0; i <= s.length; i++) {
const isCur = i === st.i;
const cls = isCur ? 'orange' : (st.dp[i] ? 'green' : 'default');
viz += `<span class="chip ${cls}" style="min-width:32px;font-size:12px;height:28px;">${st.dp[i]?'T':'F'}</span>`;
}
viz += '</div>';
viz += '<div style="margin-top:8px;"><b>字典:</b></div>';
viz += '<div style="display:flex;gap:4px;flex-wrap:wrap;margin:4px 0;">';
wordDict.forEach(w => {
const isMatch = w === st.matchWord;
const cls = isMatch ? 'green' : 'default';
viz += `<span class="chip ${cls}" style="min-width:auto;padding:4px 10px;font-size:13px;">"${w}"</span>`;
});
viz += '</div>';
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + st.msg + '</div>';
if (st.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">${st.matched ? `"${s}" 可以被分割 ✅` : `"${s}" 无法被分割 ❌`}</div>`;
}
$('hintText').textContent = st.msg;
const stages = ['init→初始化','checkI→检查','tryJ→尝试','found→找到','fail→失败','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 = 's="leetcode", dict=["leet","code"]';
buildSteps(examples[0].input, examples[0].dict);
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="([^"]+)"\s*,\s*dict=\[([^\]]+)\]/);
if (!m) { alert('格式: s="leetcode", dict=["leet","code"]'); return; }
const dict = m[2].match(/"([^"]*)"/g).map(x => x.replace(/"/g, ''));
buildSteps(m[1], dict);
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}", dict=["${e.dict.join('","')}"]`;
buildSteps(e.input, e.dict); 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 wordBreak(s, wordDict):
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
word_set = set(wordDict)
for i in range(1, n + 1):
for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break
return dp[n]`, {lang:'Python'});
})();
</script>
</body>
</html>