Loading...
More JavaScript Posts
const longestPalindrome = (s) => {if(s.length === 1) return sconst odd = longestOddPalindrome(s)const even = longestEvenPalindrome(s)if(odd.length >= even.length) return oddif(even.length > odd.length) return even};const longestOddPalindrome = (s) => {let longest = 0let longestSubStr = ""for(let i = 1; i < s.length; i++) {let currentLongest = 1let currentLongestSubStr = ""let left = i - 1let right = i + 1while(left >= 0 && right < s.length) {const leftLetter = s[left]const rightLetter = s[right]left--right++if(leftLetter === rightLetter) {currentLongest += 2currentLongestSubStr = s.slice(left+1, right)} else break}if(currentLongest > longest) {if(currentLongestSubStr) longestSubStr = currentLongestSubStrelse longestSubStr = s[i]longest = currentLongest}}return longestSubStr}const longestEvenPalindrome = (s) => {let longest = 0let longestSubStr = ""for(let i = 0; i < s.length - 1; i++) {if(s[i] !== s[i+1]) continue;let currentLongest = 2let currentLongestSubStr = ""let left = i - 1let right = i + 2while(left >= 0 && right < s.length) {const leftLetter = s[left]const rightLetter = s[right]left--right++if(leftLetter === rightLetter) {currentLongest += 2currentLongestSubStr = s.slice(left+1, right)} else break}if(currentLongest > longest) {if(currentLongestSubStr) longestSubStr = currentLongestSubStrelse longestSubStr = s[i] + s[i+1]longest = currentLongest}}return longestSubStr}console.log(longestPalindrome("babad"))
const permutations = arr => {if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;return arr.reduce((acc, item, i) =>acc.concat(permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item,...val,])),[]);};permutations([1, 33, 5]);// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ]
// `date` is a `Date` objectconst formatYmd = date => date.toISOString().slice(0, 10);// ExampleformatYmd(new Date()); // 2020-05-06
var invertTree = function(root) {const reverseNode = node => {if (node == null) {return null}reverseNode(node.left);reverseNode(node.right);let holdLeft = node.left;node.left = node.right;node.right = holdLeft;return node;}return reverseNode(root);};
const countSubstrings = (str, searchValue) => {let count = 0,i = 0;while (true) {const r = str.indexOf(searchValue, i);if (r !== -1) [count, i] = [count + 1, r + 1];else return count;}};countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3countSubstrings('tutut tut tut', 'tut'); // 4
const flat = arr => [].concat.apply([], arr.map(a => Array.isArray(a) ? flat(a) : a));// Orconst flat = arr => arr.reduce((a, b) => Array.isArray(b) ? [...a, ...flat(b)] : [...a, b], []);// Or// See the browser compatibility at https://caniuse.com/#feat=array-flatconst flat = arr => arr.flat();// Exampleflat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']