<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <link rel="stylesheet" href="css.css"> <script src="js.js"></script> </head> <body> <div> <h2>寻找字符串中出现字符最多的次数,出现次数最多的字符,出现次数最多的字符的索引</h2> <input type="text" placeholder="请输入字符串"> <button>计算</button> <br> 出现字符最多的次数: <input type="text" /> <br> 出现次数最多的字符: <input type="text" /> <br> 出现次数最多的字符的索引: <input type="text" /> </div> </body> </html>
css.css
div { width: 800px; height: 200px; background: #f1f1f1; margin: 0 auto; text-align: center; line-height: 20px; border: 1px solid #ccc; border-radius: 10px; } h2 { font-size: 20px; width: 100%; } button { cursor: pointer; background: #eee; border: 1px solid #ddd; } input { width: 165px; height: 25px; border: 1px solid #ddd; }
js.js
window.onload = function() { var oBtn = document.getElementsByTagName("button"); var oIpt = document.getElementsByTagName("input"); oBtn[0].onclick = function() { var str = oIpt[0].value; var objChar = {}; for (var i = 0; i < str.length; i++) { var char = str.charAt(i); if (objChar[char]) { objChar[char] += 1; } else { objChar[char] = 1; } } var maxCount = 0; var maxCharIndex = []; for (var key in objChar) { if (maxCount < objChar[key]) { maxCount = objChar[key]; maxCharIndex = []; maxCharIndex.push(key); } else if (maxCount == objChar[key]) { maxCharIndex.push(key); } } function getCount() { return maxCount; } function getmaxChar() { return maxCharIndex; } var objIndex = {}; var maxIndex = []; for (var j = 0; j < maxCharIndex.length; j++) { for (var i = 0; i < str.length; i++) { if (str[i] == maxCharIndex[j]) { maxIndex.push(i); } if (i == str.length - 1) { objIndex[maxCharIndex[j]] = maxIndex; maxIndex = []; } } } function getIndex() { var maxIndex2 = []; for (var key in objIndex) { maxIndex2.push(key + "的索引为(" + objIndex[key] + ")"); } return maxIndex2; } oIpt[1].value = getCount(); oIpt[2].value = getmaxChar(); oIpt[3].value = getIndex(); } }
时间: 2024-10-13 09:06:18