# My Leetcode Solution (Medium 1 - 2000) ###### tags: `Other` :::warning [TOC] ::: --- ### []() > ##### []() > [color=#6CE26C] ```javascript= ``` --- ### [1306. Jump Game III](https://leetcode.com/problems/jump-game-iii/) > ##### [Runtime: 95.94% / Memory: 30.49%](https://leetcode.com/problems/jump-game-iii/submissions/875449231/) > [color=#6CE26C] ```javascript= var canReach = function(arr, start) { let memo = Array(arr.length).fill(true) function run( idx ){ const num = arr[idx] if ( num === 0 ){ return true } let add = false if ( memo[idx + num] ){ memo[idx + num] = false add = run( idx + num ) } let minus = false if ( memo[idx - num] ){ memo[idx - num] = false minus = run(idx - num) } return add || minus } return run(start) }; ``` --- ### [1191. K-Concatenation Maximum Sum](https://leetcode.com/problems/k-concatenation-maximum-sum/) > ##### [Runtime: 75% / Memory: 8.33%](https://leetcode.com/problems/k-concatenation-maximum-sum/submissions/866368224/) > [color=#6CE26C] ```javascript= var kConcatenationMaxSum = function(arr, k) { let module = (10**9 + 7) let max = 0 let repeat = 0 if ( k >= 2 ){ repeat = arr.reduce( (acc, val) => acc + val, 0) arr = arr.concat(arr) } let cnt = 0 arr.reduce((acc, val) => { cnt += val if ( cnt > 0 ){ max = Math.max( max, cnt ) } else { cnt = 0 } return acc + val }, 0) if ( repeat > 0 ){ return ( k >= 2 ) ? (repeat * (k-2) + max) % (10**9 + 7) : max % module } else { return ( max > 0 ) ? max % module : 0 } }; ``` --- ### [1011. Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) > ##### [Runtime: 9.70% / Memory: 56.72%](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/submissions/866369198/) > [color=#6CE26C] ```javascript= var shipWithinDays = function(weights, days) { let total = 0 let min = 0 for (let i=0; i<weights.length; i++){ total += weights[i] min = Math.max( min, weights[i] ) } let avg = Math.ceil(total / days) let guessP = Math.max( min, avg ) while ( true ){ let rDays = days let packs = 0 for ( let i=0; i<weights.length; i++ ){ packs += weights[i] if ( packs > guessP ){ rDays -- packs = weights[i] } if ( rDays === 0 ){ break } if ( i === weights.length - 1 ){ return guessP } } guessP ++ } }; ``` --- ### [994. Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) Runtime: 97 ms, faster than 75.82% of JavaScript online submissions for Rotting Oranges. Memory Usage: 46 MB, less than 21.68% of JavaScript online submissions for Rotting Oranges. ```javascript= var orangesRotting = function(grid) { let cnt = 0 while (true){ let hasRott = 0 let hasFresh = false let rottGrid = JSON.parse(JSON.stringify(grid)) for (let row=0; row<grid.length; row++){ for (let col=0; col<grid[row].length; col++){ if ( grid[row][col] === 1 ){ hasFresh = true } if ( grid[row][col] === 2 ){ [[-1,0],[+1,0],[0,-1],[0,+1]].forEach( d => { if ( grid[row+d[0]] && grid[row+d[0]][col+d[1]] === 1 ){ rottGrid[row+d[0]][col+d[1]] = 2 hasRott ++ } }) } } } grid = rottGrid if ( hasRott === 0 ){ if ( hasFresh ){ return -1 } return cnt } cnt ++ } }; ``` --- ### [990. Satisfiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/) Runtime: 118 ms, faster than 68.33% of JavaScript online submissions for Satisfiability of Equality Equations. Memory Usage: 45.5 MB, less than 90.00% of JavaScript online submissions for Satisfiability of Equality Equations. ```javascript= var equationsPossible = function(equations) { let same = [] // [ Set(), ...] let diff = [] // [ [], ... ] for( let [v1, eq, , v2] of equations ){ // make Data if ( eq === '=' ){ // same let grpI = new Set() for( let i in same ){ if ( same[i].has( v1 ) || same[i].has( v2 ) ){ same[i].add( v1 ) same[i].add( v2 ) grpI.add( i ) } } if ( grpI.size === 0 ){ // 沒重複,代表不同組 same.push( new Set([v1,v2]) ) } if ( grpI.size === 2 ){ // 兩處重複,必須合併 let gI = [...grpI] same[gI[0]] = new Set( [ ...same[gI[0]], ...same.splice( gI[1], 1)[0] ] ) } } else if ( eq === '!' ){ // diff if ( v1 === v2 ){ return false } diff.push( [v1,v2] ) } } for (let s of same){ for (let d of diff){ if ( s.has(d[0]) && s.has(d[1]) ){ return false } } } return true }; ``` --- ### [985. Sum of Even Numbers After Queries]() Runtime: 193 ms, faster than 57.57% of JavaScript online submissions for Sum of Even Numbers After Queries. Memory Usage: 50.5 MB, less than 59.09% of JavaScript online submissions for Sum of Even Numbers After Queries. ```javascript= var sumEvenAfterQueries = function(nums, queries) { let sum = nums.reduce( (acc,val) => { if ( val % 2 === 0 ){ return acc + val } return acc }, 0 ) let res = [] for (let [add, key] of queries){ let preVal = nums[key] nums[key] += add if ( preVal % 2 === 0 ){ sum -= preVal } if ( nums[key] % 2 === 0 ){ sum += nums[key] } res.push(sum) } return res }; ``` --- ### [973. K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) Runtime: 202 ms, faster than 96.76% of JavaScript online submissions for K Closest Points to Origin. Memory Usage: 53.2 MB, less than 95.04% of JavaScript online submissions for K Closest Points to Origin. ```javascript= var kClosest = function(points, k) { function dist([x,y]){ return x**2 + y**2 } points.sort( (a,b) => dist(a) - dist(b) ) return points.slice(0,k) }; ``` --- ### [740. Delete and Earn](https://leetcode.com/problems/delete-and-earn/) Runtime: 95 ms, faster than 77.38% of JavaScript online submissions for Delete and Earn. Memory Usage: 45.6 MB, less than 56.94% of JavaScript online submissions for Delete and Earn. ```javascript= var deleteAndEarn = function(nums) { let map = {} for (let n of nums){ map[n] = map[n] ? map[n] + n : n } let N = [...new Set(nums)].sort((a,b)=>a-b) let dp = Array( N.length ).fill(0) for( let i=0; i < N.length; i++ ){ let key = N[i] if ( N[i-1] === undefined ){ // 陣列前1個不存在 dp[i] = map[key] continue; } if ( N[i-1] !== key-1 ){ // 前1陣列 key !== 本陣列 key-1 dp[i] = dp[i-1] + map[key] continue; } if ( N[i-2] === undefined ){ // 陣列前2個不存在 dp[i] = Math.max( map[key], dp[i-1] ) continue; } dp[i] = Math.max( dp[i-2] + map[key], dp[i-1] ) } return dp.at(-1) }; ``` --- ### [658. Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) Runtime: 129 ms, faster than 70.83% of JavaScript online submissions for Find K Closest Elements. Memory Usage: 49.3 MB, less than 40.24% of JavaScript online submissions for Find K Closest Elements. ```javascript= var findClosestElements = function(arr, k, x) { let map = arr.map( e => e - x ) let idx = map.findIndex( e => e >= 0 ) if ( idx === -1 ){ idx = map.length } let pos = map.splice(idx, map.length) let neg = [...map].map( e => e * -1 ).reverse() let posCnt = idx let negCnt = idx while( k > 0 ){ let nD = neg[0] === undefined ? Infinity : neg[0] let pD = pos[0] === undefined ? Infinity : pos[0] if ( nD <= pD ){ neg.shift() negCnt -- } else { pos.shift() posCnt ++ } k-- } return arr.slice(negCnt, posCnt) }; ``` --- ### [542. 01 Matrix](https://leetcode.com/problems/01-matrix/) Runtime: 223 ms, faster than 76.66% of JavaScript online submissions for 01 Matrix. Memory Usage: 48.5 MB, less than 99.68% of JavaScript online submissions for 01 Matrix. ```javascript= var updateMatrix = function(mat) { let rowLen = mat.length let colLen = mat[0].length for( let r=0; r<rowLen; r++ ){ for( let c=0; c<colLen; c++ ){ if ( mat[r][c] === 0 ){ continue } mat[r][c] = Infinity if ( c > 0 ){ // left mat[r][c] = mat[r][c-1] + 1 } if ( r > 0 ){ // top mat[r][c] = Math.min( mat[r][c], mat[r-1][c] + 1) } } } for( let r=rowLen-1; r>=0; r-- ){ for( let c=colLen-1; c>=0; c-- ){ if ( mat[r][c] === 0 ){ continue } if ( c < colLen-1 ){ // right mat[r][c] = Math.min( mat[r][c], mat[r][c+1] + 1) } if ( r < rowLen-1 ){ // bottom mat[r][c] = Math.min( mat[r][c], mat[r+1][c] + 1) } } } return mat }; ``` --- ### [322. Coin Change](https://leetcode.com/problems/coin-change/) Runtime: 186 ms, faster than 53.97% of JavaScript online submissions for Coin Change. Memory Usage: 48.3 MB, less than 41.09% of JavaScript online submissions for Coin Change. ```javascript= var coinChange = function(coins, amount) { let tb = Array(amount+1).fill( Infinity ) tb[0] = 0 for ( let i=0; i<= amount; i++){ for ( let coin of coins ){ if ( tb[i + coin] === undefined ){ continue } tb[i + coin] = Math.min( tb[i + coin], tb[i] + 1 ) } } return tb[amount] === Infinity ? -1 : tb[amount] }; ``` --- ### [238. Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) Runtime: 118 ms, faster than 72.49% of JavaScript online submissions for Product of Array Except Self. Memory Usage: 55.5 MB, less than 33.61% of JavaScript online submissions for Product of Array Except Self. ```javascript= var productExceptSelf = function(nums) { let left = Array(nums.length).fill(0) let right = Array(nums.length).fill(0) for( let i=0; i<nums.length; i++){ if ( i===0 ) { left[i] = nums[i] continue } left[i] = left[i-1] * nums[i] } for( let i=nums.length-1; i>=0; i--){ if ( i===nums.length-1 ) { right[i] = nums[i] continue } right[i] = right[i+1] * nums[i] } let resArr = Array(nums.length).fill(0) for( let i=0; i<nums.length; i++){ if ( left[i-1] === undefined ){ resArr[i] = right[i+1] continue } if ( right[i+1] === undefined ){ resArr[i] = left[i-1] continue } resArr[i] = left[i-1] * right[i+1] } return resArr }; ``` --- ### [198. House Robber](https://leetcode.com/problems/house-robber/) Runtime: 94 ms, faster than 38.58% of JavaScript online submissions for House Robber. Memory Usage: 41.1 MB, less than 99.56% of JavaScript online submissions for House Robber. ```javascript= var rob = function(nums) { for (let i=2; i<nums.length; i++ ){ let gap1 = nums[i] + nums[i-2] let gap2 = nums[i] + (nums[i-3] || 0) nums[i] = Math.max( gap1, gap2 ) } return Math.max( nums[nums.length-2] || 0, nums[nums.length-1] || 0) }; ``` --- ### [150. Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) Runtime: 111 ms, faster than 54.92% of JavaScript online submissions for Evaluate Reverse Polish Notation. Memory Usage: 45.7 MB, less than 31.31% of JavaScript online submissions for Evaluate Reverse Polish Notation. ```javascript= var evalRPN = function(tokens) { let nums = [] for ( let i=0; i<tokens.length; i++ ){ if ( Number.isNaN( +tokens[i] ) ) { let right = nums.pop() let left = nums.at(-1) nums[nums.length-1] = Calc(left, right, tokens[i]) } else { nums.push( +tokens[i] ) } } function Calc(left, right, op){ switch(op){ case '+': return left + right break; case '-': return left - right break; case '*': return left * right break; case '/': return (left / right) < 0 ? Math.ceil(left / right) : Math.floor(left / right) break; } } return nums[0] }; ``` --- ### [122. Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) > ##### [Runtime: 84.99% / Memory: 32.68%](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/submissions/875434362/) > [color=#6CE26C] ```javascript= var maxProfit = function(prices) { let res = 0; for( let i=1; i<prices.length; i++ ){ let diff = prices[i] - prices[i-1] res += ( diff > 0 ) ? diff : 0; } return res }; ``` --- ### [78. Subsets](https://leetcode.com/problems/subsets/) > ##### [Runtime: 72.56% / Memory: 53.25%](https://leetcode.com/problems/subsets/submissions/871062939/) > [color=#6CE26C] ```javascript= var subsets = function(nums) { let res = [] Run(0) function Run( index, item=[] ){ for ( let i=index; i<nums.length; i++ ){ Run( i+1, [...item, nums[i]] ) } res.push( item ) } return res }; ``` --- ### [73. Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) > ##### [Runtime: 78.90% / Memory: 16.11%](https://leetcode.com/problems/set-matrix-zeroes/submissions/868030377/) > [color=#6CE26C] ```javascript= var setZeroes = function(matrix) { const row = new Set() const col = new Set() for ( r in matrix ){ for ( c in matrix[r] ){ if ( matrix[r][c] === 0 ){ row.add(r) col.add(c) } } } for ( r in matrix ){ for ( c in matrix[r] ){ if ( row.has(r) || col.has(c) ){ matrix[r][c] = 0 } } } return matrix }; ``` --- ### [64. Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) Runtime: 65 ms, faster than 91.37% of JavaScript online submissions for Minimum Path Sum. Memory Usage: 42.8 MB, less than 80.67% of JavaScript online submissions for Minimum Path Sum. ```javascript= var minPathSum = function(grid) { let yLast = grid.length-1 let xLast = grid[0].length-1 grid.forEach((c,y)=>{ grid[y].forEach((r,x)=>{ let up = Infinity let left = Infinity if ( x===0 && y===0 ){ return } if (x>0){ left = grid[y][x-1] } if (y>0){ up = grid[y-1][x] } grid[y][x] += Math.min(left,up) }) }) return grid[yLast][xLast] }; ``` --- ### [63. Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) > ##### [Runtime: 95.98% / Memory: 85.19%](https://leetcode.com/problems/unique-paths-ii/submissions/867961271/) > [color=#6CE26C] ```javascript= var uniquePathsWithObstacles = function(obstacleGrid) { obstacleGrid[0][0] = (obstacleGrid[0][0] === 0) ? 1 : 0 for (let r=0; r<obstacleGrid.length; r++){ for (let c=0; c<obstacleGrid[0].length; c++){ if ( obstacleGrid[r][c] === 1 && r + c !== 0 ){ obstacleGrid[r][c] = 0 continue } obstacleGrid[r][c] += (obstacleGrid?.[r-1]?.[c] || 0) + (obstacleGrid?.[r]?.[c-1] || 0) } } return obstacleGrid.at(-1).at(-1) }; ``` --- ### [62. Unique Paths](https://leetcode.com/problems/unique-paths/) > ##### [Runtime: 97.83% / Memory: 75.44%](https://leetcode.com/problems/unique-paths/submissions/867954733/) > [color=#6CE26C] ```javascript= var uniquePaths = function(m, n) { let arr = Array.from({length: m},(e)=> Array(n).fill(1)) for (let r=1; r<m; r++){ for (let c=1; c<n; c++){ arr[r][c] = arr[r-1][c] + arr[r][c-1] } } return arr[m-1][n-1] }; ``` --- ### [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii) > ##### [Runtime: 59.2% / Memory: 54.71%](https://leetcode.com/problems/spiral-matrix-ii/submissions/871806833/) > [color=#6CE26C] ```javascript= var generateMatrix = function(n) { const res = Array.from({length: n}, (e) => Array(n).fill(0)) let num = 1 let row = 0 let col = -1 let add = [{r:0,c:1}, {r:1,c:0}, {r:0,c:-1}, {r:-1,c:0}] let D = 0 while( num <= n*n ){ row += add[D].r col += add[D].c if ( res?.[row]?.[col] !== 0 ){ row -= add[D].r col -= add[D].c D += ( D === 3 ) ? -3 : 1 continue } res[row][col] = num num ++ } return res }; ``` --- ### [57. Insert Interval]() Runtime: 108 ms, faster than 50.85% of JavaScript online submissions for Insert Interval. Memory Usage: 44.6 MB, less than 26.29% of JavaScript online submissions for Insert Interval. ```javascript= var insert = function(intervals, newInterval) { let [st,ed] = newInterval let st_inside = intervals.findIndex( ( [iSt,iEd] ) => iSt <= st && st <= iEd ) let ed_inside = intervals.findIndex( ( [iSt,iEd] ) => iSt <= ed && ed <= iEd ) let stIdx, stVal if ( st_inside > -1 ){ stIdx = st_inside stVal = intervals[stIdx][0] } else { let st_small = intervals.findIndex( ( [iSt,iEd] ) => st < iSt ) stIdx = st_small > -1 ? st_small : Infinity stVal = st } let edIdx, edVal if ( ed_inside > -1 ){ edIdx = ed_inside edVal = intervals[edIdx][1] } else { let ed_small = intervals.findIndex( ( [iSt,iEd] ) => ed < iEd ) edIdx = ed_small > -1 ? ed_small-1 : Infinity edVal = ed } intervals.splice( stIdx, edIdx-stIdx+1, [stVal, edVal] ) return intervals }; ``` --- ### [55. Jump Game](https://leetcode.com/problems/jump-game/) > ##### [Runtime: 99.69% / Memory: 67.33%](https://leetcode.com/problems/jump-game/submissions/810560955/) > [color=#6CE26C] ```javascript= var canJump = function(nums) { let hst = 0 for(let i=0; i<nums.length; i++){ hst = Math.max(nums[i], hst) hst -- if ( hst === -1 && i !== nums.length-1 ){ return false } } return true }; ``` --- ### [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) > ##### [Runtime: 61.2% / Memory: 91.85%](https://leetcode.com/problems/maximum-subarray/submissions/811345869/) > [color=#6CE26C] ```javascript= var maxSubArray = function(nums) { let prev = 0; let max = -Infinity; for (var i = 0; i < nums.length; i++) { prev = Math.max(prev + nums[i], nums[i]); max = Math.max(max, prev); } return max; }; ``` --- ### [49. Group Anagrams](https://leetcode.com/problems/group-anagrams/) > ##### [Runtime: 65.20% / Memory: 31.91%](https://leetcode.com/problems/group-anagrams/submissions/871012602/) > [color=#6CE26C] ```javascript= var groupAnagrams = function(strs) { const obj = {} for ( let str of strs ){ let key = str.split('').sort().join() if ( obj[key] ){ obj[key].push(str) } else { obj[key] = [str] } } return [ ...Object.values(obj) ] }; ``` --- ### [48. Rotate Image](https://leetcode.com/problems/rotate-image/) > ##### [Runtime: 92.69% / Memory: 99.28%](https://leetcode.com/problems/rotate-image/submissions/866364123/) > [color=#6CE26C] ```javascript= var rotate = function(matrix) { const len = matrix.length for ( let r=0; r<len; r++ ){ for ( let c=0; c<len; c++ ){ if ( r >= c ){ continue } let num = matrix[r][c] matrix[r][c] = matrix[c][r] matrix[c][r] = num } matrix[r].reverse() } }; ``` --- ### [46. Permutations](https://leetcode.com/problems/permutations/) > ##### [Runtime: 99.62% / Memory: 73.46%](https://leetcode.com/problems/permutations/submissions/867976876/) > [color=#6CE26C] ```javascript= var permute = function(nums) { let res = [] Run( nums ) function Run( remainArr, newArr = [] ){ if ( remainArr.length === 1 ){ newArr.push( remainArr[0] ) res.push( newArr ) return } for ( let i=0; i<remainArr.length; i++ ){ let remA = [...remainArr] let newA = [...newArr] remA.splice(i,1) newA.push( remainArr[i] ) Run( remA, newA ) } } return res }; ``` --- ### [45. Jump Game II](https://leetcode.com/problems/jump-game-ii/) > ##### [Runtime: 36.48% / Memory: 27.47%](https://leetcode.com/problems/jump-game-ii/submissions/871056586/) > [color=#6CE26C] ```javascript= var jump = function(nums) { const len = nums.length const dp = Array(len).fill(Infinity) dp[0] = 0 for ( let i=0; i<len; i++ ){ for ( let j=i+1; j<=i+nums[i] && j<len; j++ ){ dp[j] = Math.min( dp[j], dp[i] + 1 ) } } return dp[len-1] }; ``` --- ### [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) > ##### [Runtime: 87.1% / Memory: 41.26%](https://leetcode.com/problems/letter-combinations-of-a-phone-number/submissions/871810484/) > [color=#6CE26C] ```javascript= var letterCombinations = function(digits) { if ( digits.length === 0 ) { return [] } const map = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } let res = [] function run(str, idx){ if ( idx === digits.length ){ res.push(str) return } let mVals = map[digits[idx]] // 'abc' for ( let i=0; i<mVals.length; i++ ){ run( str + mVals[i], idx + 1 ) // 'def' } idx ++ } run('', 0) return res }; ``` --- ### [15. 3Sum](https://leetcode.com/problems/3sum/) Runtime: 223 ms, faster than 51.40% of JavaScript online submissions for 3Sum. Memory Usage: 52.2 MB, less than 84.35% of JavaScript online submissions for 3Sum. ```javascript= var threeSum = function(nums) { nums.sort((a,b)=>a-b) let filterNums = [ ...new Set(nums)] let numMap = new Map() nums.forEach((n,i)=>{ if ( numMap.has(n) ){ numMap.set(n, numMap.get(n) + 1 ) } else { numMap.set(n,1) } }) let res = [] for (let i=0; i<filterNums.length; i++ ){ if ( filterNums[i] > 0 ) { break } let num1 = filterNums[i] for (let j=i; j<filterNums.length; j++){ let num2 = filterNums[j] let num3 = -( num1 + num2 ) if ( num1 === 0 ){ if ( numMap.get(0) >= 3 ){ res.push([0,0,0]) } break } if ( num1 === num2 && numMap.get( num1 ) < 2 ){ continue } if ( numMap.has( num3 ) && num3 >= num2 ){ if ( num3 === num1 && numMap.get( num3 ) < 2 ){ continue } if ( num3 === num2 && numMap.get( num3 ) < 2 ){ continue } let arr = [ num1, num2, num3 ] res.push(arr) } } } return res }; ``` --- ### [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/) Runtime: 105 ms, faster than 68.96% of JavaScript online submissions for Container With Most Water. Memory Usage: 49.5 MB, less than 73.50% of JavaScript online submissions for Container With Most Water. ```javascript= var maxArea = function(height) { let start = 0 let end = height.length - 1 let max = 0 while ( start < end ){ let waterHeight = Math.min( height[start], height[end] ) max = Math.max( max, (end - start) * waterHeight ) if ( height[start] < height[end] ){ // 高者留下 start++ } else { end-- } } return max }; ``` --- ### [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/) Runtime: 80 ms, faster than 89.81% of JavaScript online submissions for Reverse Integer. Memory Usage: 43.8 MB, less than 66.51% of JavaScript online submissions for Reverse Integer. ```javascript= /** * @param {number} x * @return {number} */ var reverse = function(x) { let res = +String( Math.abs(x) ).split('').reverse().join('') res = res < (2**31 - 1) ? res : 0 return res * Math.sign(x) }; ``` --- ### [5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) Runtime: 154 ms, faster than 68.60% of JavaScript online submissions for Longest Palindromic Substring. Memory Usage: 51.6 MB, less than 15.98% of JavaScript online submissions for Longest Palindromic Substring. ```javascript= var longestPalindrome = function(s) { let longestStr = s[0] let idx = 0 while( idx < s.length ){ let str = s[idx] let beside = true // 緊鄰重複字 let besideEndIdx = idx do { if ( s[besideEndIdx + 1] && s[idx] === s[besideEndIdx + 1] ){ str += s[idx] besideEndIdx ++ } else { beside = false } } while( beside ) let between = true // 對角重複字 let betweenAdd = 1 do { if ( s[idx - betweenAdd] && s[besideEndIdx + betweenAdd] && s[idx - betweenAdd] === s[besideEndIdx + betweenAdd] ){ str = s[idx - betweenAdd] + str + s[besideEndIdx + betweenAdd] betweenAdd ++ } else { between = false } } while( between ) if ( str.length > longestStr.length ){ longestStr = str } idx = besideEndIdx + 1 } return longestStr }; ``` --- ### [3. Longest Substring Without Repeating Characters](https://https://leetcode.com/problems/longest-substring-without-repeating-characters/) Runtime: 89 ms, faster than 89.62% of JavaScript online submissions for Longest Substring Without Repeating Characters. Memory Usage: 48 MB, less than 58.88% of JavaScript online submissions for Longest Substring Without Repeating Characters. ```javascript= var lengthOfLongestSubstring = function(s) { let max = s.length > 0 ? 1 : 0 let str = '' for( let i=0; i<s.length; i++ ){ str += s[i] let repeatIndex = str.indexOf(s[i+1]) if ( repeatIndex !== -1 || i == s.length - 1 ){ max = Math.max( max, str.length ) str = str.slice( repeatIndex + 1 ) } } return max }; ```