// Array methods const isPalindromicA = w => w === w.split('').reverse().join('');
// while loop const isPalindromicB = (w) => { let len = w.length; // 感谢 @拉比克魔王 的指点 let start = Math.ceil(len / 2); while (start < len) { if (w[start] !== w[len - start - 1]) { returnfalse; } start++; } returntrue; };
// ------------------------------------------------- // perf test // first let's generate a fake word with, say 20 chars var word = (function () { var len = 20; var arr = []; while (len--) { arr.push(97 + ((Math.random()* 26) | 0)); } returnString.fromCharCode.apply(String, arr); })();
// times var t = 2e4; var i = 0;
console.time('Array method'); while (i < t) { isPalindromicA(word); i++; } console.timeEnd('Array method');
i = 0; console.time('Loop'); while (i < t) { isPalindromicB(word); i++; } console.timeEnd('Loop');
while (temp = regex.exec(chars)) { if (temp[0].length > max) { char = temp[1]; max = temp[0].length; } } return char; };
// see http://www.jackpu.com/qian-duan-mian-shi-zhong-de-chang-jian-de-suan-fa-wen-ti/ var findMaxDuplicateCharNormal = function(str) { if (str.length == 1) { return str; } let charObj = {}; for (let i = 0; i < str.length; i++) { if (!charObj[str.charAt(i)]) { charObj[str.charAt(i)] = 1; } else { charObj[str.charAt(i)] += 1; } } let maxChar = '', maxValue = 1; for (var k in charObj) { if (charObj[k] >= maxValue) { maxChar = k; maxValue = charObj[k]; } } return maxChar; };
// ------------------------------------------------- // perf test
// first let's generate a random string with 30 chars var chars = (function () { var len = 30; var arr = []; while (len--) { arr.push(97 + ((Math.random()* 26) | 0)); } returnString.fromCharCode.apply(String, arr); })();
// times var t = 2e4; var i;
i = 0; console.time('正常方法'); while (i < t) { findMaxDuplicateCharNormal(chars); i++; } console.timeEnd('正常方法');
i = 0; console.time('正则方法'); while (i < t) { findMaxDuplicateCharRegex(chars); i++; } console.timeEnd('正则方法');
array = array.reduce(([max, min], el) => { max = el > max ? el : max; min = el < min ? el : min; return [max, min]; }, array);
return array[0] - array[1]; };
// see http://www.jackpu.com/qian-duan-mian-shi-zhong-de-chang-jian-de-suan-fa-wen-ti/ functiongetMaxProfit(arr) { var minPrice = arr[0]; var maxProfit = 0;
for (var i = 0; i < arr.length; i++) { var currentPrice = arr[i];