-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStrings.html
More file actions
48 lines (40 loc) · 1.35 KB
/
Strings.html
File metadata and controls
48 lines (40 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html>
<head>
<title>Longest Palindromic Substring</title>
</head>
<body>
<h2>Find Longest Palindromic Substring</h2>
<input type="text" id="inputString" placeholder="Enter a string">
<button onclick="handleFindPalindrome()">Find Longest Palindrome</button>
<p><strong>Longest Palindromic Substring:</strong> <span id="result"></span></p>
<script>
function findLongestPalindrome(str) {
if (!str || str.length < 1) return "";
let start = 0, end = 0;
for (let i = 0; i < str.length; i++) {
let len1 = expandFromCenter(str, i, i);
let len2 = expandFromCenter(str, i, i + 1);
let len = Math.max(len1, len2);
if (len > end - start) {
start = i - Math.floor((len - 1) / 2);
end = i + Math.floor(len / 2);
}
}
return str.substring(start, end + 1);
}
function expandFromCenter(s, left, right) {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--;
right++;
}
return right - left - 1;
}
function handleFindPalindrome() {
const input = document.getElementById('inputString').value;
const result = findLongestPalindrome(input);
document.getElementById('result').innerText = result;
}
</script>
</body>
</html>