An algorithm every day will keep your brain from getting rusty (true rhyme)

Front-end interview question bank ( essential for interviews) Recommended: ★★★★★            

Address: Front-end interview question bank

 My cousin made her own five-star red flag National Day avatar with just one click. It’s super nice.

Preface

Looking at the algorithm will indeed make the coding ideas different. After looking at the good solution, you will feel that your own is very good low. Starting from this year, I will try to solve an algorithm problem every day, test myself to death, and update it in the long term.

Question

Given a string s that only includes '(', ')', '{', '}', '[', ']', determine whether the string is valid. A valid string must satisfy:

  1. The opening bracket must be closed by a closing bracket of the same type.
  2. Opening brackets must be closed in the correct order

Example:

示例 1:
输入:s = "()"
输出:true

示例 2:
输入:s = "()[]{}"
输出:true

示例 3:
输入:s = "(]"
输出:false

示例 4:
输入:s = "([)]"
输出:false

示例 5:
输入:s = "{[]}"
输出:true

Answer

Idea: Symmetry conforms to the last-in-first-out characteristic of the stack

// const s = '{[()]}'
const s = '()[]{}'
const arr = s.split('')
const obj = {
  "(": ")",
  "[": "]",
  "{": "}"
}
const stack = []
const valdate = data => {
  if (!data || data.length % 2 !== 0) return false
  let isRight = true
  data.split('').forEach(item => {
    if (obj[item]) {
      stack.push(item)
    } else {
      if (!stack.length || obj[stack.pop()] !== item) {
        isRight = false
      }
    }
  })
  if (stack.length) isRight = false
  return isRight
}
console.log(valdate(s)) // true

2023-02-02

Question

Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target, and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

输入:nums = [3,2,4], target = 6
输出:[1,2]

输入:nums = [3,3], target = 6
输出:[0,1]

Advanced: Can you come up with an algorithm with time complexity less than O(n2)?

Answer

  const nums = [2, 7, 11, 15], target = 9;
  // const nums = [3, 2, 4], target = 6
  // const nums = [3, 3], target = 6
  // const twoSum = function(nums, target) {
  //   let i = 0
  //   let next
  //   let isFind = false
  //   while(i < nums.length - 1 && !next) {
  //     const current = nums[i]
  //     if (current >= 9) {
  //       i++
  //     } else {
  //       nums.forEach((item, index) => {
  //         if (i !== index && item + current === target) {
  //           next = index
  //         }
  //       })
  //       if (!next) i++
  //     }
  //   }
  //   if (next) {
  //     return [i, next]
  //   }
  // }
  // console.log(twoSum(nums, target))
  // 减少一层循环(时间复杂度)
  var twoSum = function(nums, target) {
    const map = new Map();
    for(let i = 0, len = nums.length;i < len;i++) {
      if(map.has(target - nums[i])) {
          return [map.get(target - nums[i]), i];
      }
      map.set(nums[i], i);
    }
    return [];
  };
  console.log(twoSum(nums, target))

2023-02-03

Question

Given a string s, please find the length of the longest consecutive substring that does not contain repeated characters.

输入: s = "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子字符串是 "abc",所以其长度为 3。

输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子字符串是 "b",所以其长度为 1。

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

输入: s = ""
输出: 0

Answer

// 方便参考,输出连带字符串结果
const s = 'abcabcbb'
// const s = "bbbbb"
// const s = "pwwkew"
// const s = ''
const lengthOfLongestSubstring = (s) => {
  let str = ''
  let index = 0
  let obj = { len: index, str }
  if (!s) return obj
  s.split('').forEach(item => {
    if(str.includes(item)) {
      const { len } = obj
      if (index > len) obj = { len: index, str }
      index = 1
      str = item
    } else {
      str += item
      index++
    }
  })
  return obj
}
const { len, str } = lengthOfLongestSubstring(s)
console.log(len, str)

Question

You are given an integer array nums. The elements in the array are different from each other. Returns all possible subsets (power sets) of this array.

The solution set cannot contain duplicate subsets. You can return the solution sets in any order.

输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

输入:nums = [0]
输出:[[],[0]]

Answer

const nums = [1, 2, 3]
// const subsets = nums => {
//   if (nums.length === 0) return [[]];
//   let resArr = [];
//   backtrack(nums, 0, [], resArr);
//   return resArr;
// };
// function backtrack(nums, index, subArr, resArr) {
//   if (Array.isArray(subArr)) {
//     resArr.push(subArr.slice());
//   }
//   if (index === nums.length) {
//     return;
//   } 
//   for (let i = index; i < nums.length; i++) {
//     subArr.push(nums[i]);
//     backtrack(nums, i + 1, subArr, resArr);
//     subArr.pop();
//   }
// }
// subsets(nums)
const getAllSubsets = nums => nums.reduce(
  (subsets, value) => subsets.concat(
    subsets.map(set => [value,...set])
  ),
[[]]);

console.log(getAllSubsets(nums));

Question

Write a function to find the longest common prefix in an array of strings.

If no common prefix exists, the empty string "" is returned.

输入:strs = ["flower","flow","flight"]
输出:"fl"

输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

Answer

// 如何减少遍历?这么搞打败不了对手啊
const strs = ["flower","flow","flight"]
// const strs = ["dog","racecar","car"]
// const strs = ["aab123v", 'aab123b', 'aba123a']
const longestCommonPrefix = strs => {
  strs.sort((a, b) => a.length - b.length)
  const [firtst, ...others] = strs
  let s = ''
  let isOver = false
  for(let i = 0; i < firtst.length; i++) {
    others.forEach(item => {
      if (item[i] !== firtst[i]) isOver = true
    })
    if (!isOver) {
      s += firtst[i]
    }
  }
  return s
};
longestCommonPrefix(strs)

feel

Persistence is really difficult. When you are busy with various things in work and life, you don’t have time. I have only been doing it for a week and I can’t persist anymore. I’m willing to lose even if I lose.

Front-end interview question bank ( essential for interviews) Recommended: ★★★★★            

Address: Front-end interview question bank

 My cousin made her own five-star red flag National Day avatar with just one click. It’s super nice.

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/133386339