返回

前端算法精选(第 3 期):字符串系列攻略

前端

字符串系列算法实战

本期前端算法精选聚焦于字符串,涵盖了大厂面试中常见的难题,旨在提升你的算法思维和编程能力。

1. 栈:括号匹配问题

栈是一种先进后出(LIFO)的数据结构,广泛应用于括号匹配问题中。给定一个包含括号的字符串,你需要判断其是否匹配。

function isBalanced(str) {
  const stack = [];
  const map = { '(': ')', '[': ']', '{': '}' };

  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (map[char]) {
      stack.push(map[char]);
    } else if (stack.length && stack[stack.length - 1] === char) {
      stack.pop();
    } else {
      return false;
    }
  }

  return stack.length === 0;
}

2. 回文子串:最长回文子串算法

回文子串是指一个正向和反向读都相同的子字符串。给定一个字符串,你需要找到其最长的回文子串。

function longestPalindrome(str) {
  let start = 0;
  let end = 0;
  let maxLen = 1;

  for (let i = 0; i < str.length; i++) {
    const [left, right] = expandAroundCenter(str, i, i);
    const len = right - left + 1;

    if (len > maxLen) {
      start = left;
      end = right;
      maxLen = len;
    }

    const [left2, right2] = expandAroundCenter(str, i, i + 1);
    const len2 = right2 - left2 + 1;

    if (len2 > maxLen) {
      start = left2;
      end = right2;
      maxLen = len2;
    }
  }

  return str.substring(start, end + 1);
}

function expandAroundCenter(str, left, right) {
  while (left >= 0 && right < str.length && str[left] === str[right]) {
    left--;
    right++;
  }

  return [left + 1, right - 1];
}

3. 字符串转数字:字符串转整数算法

字符串转数字问题是指将一个表示数字的字符串转换为整数。给定一个字符串,你需要处理其可能包含的符号和空格等特殊情况。

function atoi(str) {
  str = str.trim();
  if (str.length === 0) {
    return 0;
  }

  let sign = 1;
  let i = 0;
  if (str[i] === '+' || str[i] === '-') {
    sign = str[i] === '+' ? 1 : -1;
    i++;
  }

  let result = 0;
  while (i < str.length && str[i] >= '0' && str[i] <= '9') {
    result = result * 10 + parseInt(str[i]);
    i++;
  }

  result = Math.min(Math.max(result * sign, -2 ** 31), 2 **  31 - 1);
  return result;
}

4. Unix 绝对路径:规范化路径算法

Unix 绝对路径是指从根目录到文件的完整路径。给定一个 Unix 绝对路径,你需要对其进行规范化,即简化路径并使其符合规范。

function simplifyPath(path) {
  const components = path.split('/');
  const stack = [];

  for (let component of components) {
    if (component === '.' || component === '') {
      continue;
    } else if (component === '..') {
      stack.pop();
    } else {
      stack.push(component);
    }
  }

  return '/' + stack.join('/');
}

通过剖析这些算法难题,你可以提升自己的算法思维,并在实际工作中自信应对字符串处理问题。欢迎继续关注前端算法精选系列,了解更多精彩内容!