JS Longest Palindrome Substring (Exhaustive)
JavaScript resolve longest palindrome substring problem by exhaustive.
by Tinytsunami
HTML
<div id="demo">
String = <input type="text" /> <button>Process</button>
<pre>waiting for you input something...</pre>
</div>
CSS
body {
color: #ffffff;
background: #20262e;
font-family: monospace, sans-serif;
}
#demo {
width: 400px;
padding: 5px;
}
#demo input {
color: #ffffff;
background: #20262e;
outline: none;
border: none;
border-bottom: 1px solid #ffffff;
}
#demo pre {
width: 400px;
height: 100px;
border: solid 1px #ffffff;
overflow-y: scroll;
}
#demo button {
color: #ffffff;
background: #20262e;
border: 1px solid #ffffff;
outline: none;
}
#demo button:hover {
color: #20262e;
background: #ffffff;
border: 1px solid #ffffff;
}
JavaScript
(function() {
/* get elements */
let root = document.getElementById("demo");
let inputNode = root.getElementsByTagName("input")[0];
let buttonNode = root.getElementsByTagName("button")[0];
let outputNode = root.getElementsByTagName("pre")[0];
/* check is palindrome */
let checkPalindrome = function(text, a, b) {
let len = b - a + 1;
let half = parseInt(len / 2);
for (let i = 0; i < half; i++)
if (text[a + i] != text[b - i])
return false;
return true;
};
/* evaluation time for functions */
let evaluationTime = function(f, callback) {
let start = Date.now();
let value = f();
callback.call(this, value, (Date.now() - start));
};
/* get LPS by exhaustive */
let main = function(text) {
let a, b, tmp, ans = "";
for (a = 0; a < text.length; a++)
for (b = a; b < text.length; b++)
if (checkPalindrome(text, a, b)) {
tmp = text.substring(a, b + 1);
if (ans.length < tmp.length)
ans = tmp;
}
return ans;
};
/* user input and process*/
buttonNode.onclick = function() {
evaluationTime(function() {
return main(inputNode.value);
}, function(LPS, time) {
if (LPS.length > 30)
LPS = `${LPS.substr(0, 30)}...`;
outputNode.innerHTML += `\nLPS = "${LPS}"\nTime = ${time}ms\n`;
outputNode.scrollTop = outputNode.scrollHeight;
});
};
})();