-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.js
88 lines (83 loc) · 2.33 KB
/
Solution.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
log('');
log('# s=' + s);
var sourceLength = s.length;
var length = 0;
var result = {l: 0, r: 0};
for (var mid = 0; mid < sourceLength; mid++) {
log('## mid=' + mid);
var left = mid;
var right = mid;
while (left >= 1 && right <= sourceLength - 2) {
var equal = s.charAt(left - 1) == s.charAt(right + 1);
if (equal) {
left--;
right++;
} else {
break;
}
left--;
right++;
var isEqual = s.charAt(left) == s.charAt(right);
log('left=' + left + ', right=' + right + ', isEqual=' + isEqual);
if (!isEqual) {
left++;
right--;
break;
}
}
var len = right - left + 1;
if (len >= length) {
log('update length=' + len + ', l=' + left + ', r=' + right);
length = len;
result.l = left;
result.r = right;
}
length = Math.max(right - left + 1, length);
left = mid;
right = Math.min(mid + 1, sourceLength - 1);
if (s.charAt(left) == s.charAt(right)) {
while (left >= 1 && right <= sourceLength - 2) {
left--;
right++;
if (s.charAt(left) != s.charAt(right)) {
left++;
right--;
break;
}
}
len = right - left + 1;
if (len >= length) {
// update result
length = len;
result.l = left;
result.r = right;
}
}
}
return s.substr(result.l, result.r - result.l + 1);
};
var debug = false
var log = function(str) {
if (debug) { console.log(str); }
};
function test() {
var strs = [
["babad", "bab"],
["cbbd", "bb"],
["abcba", "abcba"],
["aaaa", "aaaa"]
];
for (var i = 0; i < strs.length; i++) {
var source = strs[i][0];
var result = longestPalindrome(source);
var expect = strs[i][1];
console.log('input=' + source + ', result=' + result
+ ', ' + (result == expect));
}
}
test();