var twoSum = function (nums, target) { let newArr = [] for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] === target) { newArr.push(i, j) } } } return newArr }
优化解法 O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13
var twoSum = function (nums, target) { let arr = [] let dif let index nums.forEach((item, key) => { dif = target - item if (arr[dif] !== undefined) { index = [arr[dif], key] } arr[item] = key }) return index };
/** * @param {string} s * @return {number} */ var lengthOfLongestSubstring = function (s) { let a = [] let n = 0 for (let i = 0; i < s.length; i++) { let x = s[i] if (!a.includes(x)) { a.push(x) } else { a = [x] } n = a.length > n ? a.length : n if (n === 95) return n } s = s.slice(1) if (s.length > 0) { const n1 = lengthOfLongestSubstring(s) n = n1 > n ? n1 : n } return n };
/** * @param {string} s * @return {number} */ var lengthOfLongestSubstring = function (s) { let a = [] let n = 0 let n1 = 0 for (let i = 0; i < s.length; i++) { let x = s[i] if (!a.includes(x)) { a.push(x) n = a.length > n ? a.length : n if (n === 95) return n } else { a = [x] break; } } s = s.slice(1) if (s.length > 0) { n1 = lengthOfLongestSubstring(s) n = n1 > n ? n1 : n } return n };
/** * @param {string} s * @return {number} */ var lengthOfLongestSubstring = function (s) { if (!s.length) return 0 let a = {} let n = 1 for (let i = 0; i < s.length - 1; i++) { a[s[i]] = 1 let n1 = 1 for (let j = i + 1; j < s.length; j++) { if (a[s[j]]) { a = {} break; } else { a[s[j]] = 1 n1++ } n = Math.max(n1, n) } } return n };
function longestValidParentheses(s: string): number { const stack = [-1] let maxLength = 0 for (let i = 0; i < s.length; i++) { if (s[i] === '(') { stack.push(i) console.log(stack,'1',i,maxLength) continue; } stack.pop() console.log(stack,'2',i,maxLength)