/
longest_possible_chunk_palindrome.js
65 lines (54 loc) · 1.75 KB
/
longest_possible_chunk_palindrome.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// refrense https://www.geeksforgeeks.org/longest-possible-chunked-palindrome/
function findLongestPossibleChunkedPalindrome(str) {
console.log('value :', str, str.length, isChunckedPalindrom(str + ""));
}
function isChunckedLargetPalindrom(str) {
if (str.length === 1) return 1;
//console.log('str : '+isChunckedPalindrom(str+""));
// return Math.max(
// isChunckedPalindrom(str+""),
// isChunckedLargetPalindrom(str.substr(0, str.length - 1)),
// isChunckedLargetPalindrom(str.substr(1))
// )
}
function isChunckedPalindrom (str) {
let left = 0;
let right = str.length - 1;
let strCopies = str + "";
let currentChunk = "";
let count = 0;
while (left < right) {
if ( str[left] === str[right] && !currentChunk) {
strCopies = strCopies.substr(left+1, right-left-1);
left = 0;
right = strCopies.length - 1;
count += 2;
} else {
currentChunk += strCopies[left];
if (currentChunk === strCopies.substr(right)) {
count += 2;
strCopies = strCopies.substr(left+1, right-left-1);
//console.log('split ', left+1, right-left-1);
left = 0;
right = strCopies.length-1;
currentChunk = "";
} else {
left++;
right--;
}
}
//console.log('test', strCopies, currentChunk, count, left, right, Math.ceil(strCopies.length/2));
}
return count + 1;
}
// dataset
const dataset = [
"ghiabcdefhelloadamhelloabcdefghi",
"merchant",
"aba",
"antaprezatepzapreanta",
"geeksforgeeks"
]
dataset.forEach((value) => {
findLongestPossibleChunkedPalindrome(value);
})