小笔记(常见算法题)

32 阅读1分钟

2个数值相加(解决大数值问题)

function add(a, b) {

  let aa = a.toString();
  let bb = b.toString();

  //补0
  let max = Math.max(aa.length, bb.length);
  let aString = aa.padStart(max, '0');
  let bString = bb.padStart(max, '0');

  let flag = 0;
  let result = [];
  for (let m = max - 1; m >= 0; m--) {
    let [l, r] = [+aString[m], +bString[m]];
    let count = l + r + flag;

    flag = 0;
    if (count >= 10) {
      flag = 1;
    }

    //取整
    count = count % 10;
    result.unshift(count);
  }

  if (flag) result.unshift(flag);

  return result.join("");

}

记录一个字符串中单词出现的次数

或者是字符串中高频词

//将不是字符以外的都清除
let reg = /[^\w]\s*/g;
//将字符串先替换再拆开
let list = str.replace(reg, ' ').split(' ');

let map = {}
//结合数组循环进行收集
list.forEach(s => {
  //...
})

链表反转

利用哨兵

function r(head) {
  if (!head) return head;
  let sb = new ListNode(0);
  sb.next = head;
  while (head && head.next) {
    let next = head.next;
    head.next = head.next.next;
    next.next = sb.next;
    sb.next = next;
  }
  
  return sb.next;
}