var TEST = function () {
var _time = 0;
var _centers = [];
var _maxSize = 1;
function _print(arr, index) {
console.log(arr.substr(index - _maxSize, _maxSize * 2 + 1));
}
function _MatchTest(arr, index) {
if (!_isMatch(arr, index, _maxSize)) {
return;
}
// 邊界比對相等,執行內部比對
if (!_isInnerMatch(arr, index)) {
return;
}
// 內部比對相等,擴大邊界比對
var isUpdateRecord = false;
var newMaxSize = _maxSize + 1;
while (_isMatch(arr, index, (_maxSize + 1))) {
_time++;
isUpdateRecord = true;
_maxSize++;
}
_centers = isUpdateRecord ? [index] : _centers;
}
function _isMatch(arr, index, size) {
if (!arr[index-size] || !arr[index+size]) {
return false;
}
return arr[index-size] === arr[index+size];
}
function _isInnerMatch(arr, index) {
var size = _maxSize - 1;
while (size > 0) {
_time++;
if (!_isMatch(arr, index, size)) {
return false;
}
size--;
}
_centers.push(index);
return true;
}
function _reset() {
_time = 0;
_centers = [];
_maxSize = 1;
}
return {
doTest: function (str) {
if (!str) { return; }
_reset();
var slen = str.length;
for (var i=1; i<slen; i++) {
_time++;
_MatchTest(str, i);
}
var clen = _centers.length;
for (var i=0; i<clen; i++) {
_print(str, _centers[i]);
}
return _time;
}
};
}();
TEST.doTest('abebfdadgdaer');
TEST.doTest('abcscsbaaaadje');