编辑代码

// const { xcode } = require("react-syntax-highlighter/dist/esm/styles/hljs");

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
  const str = await readline();
  // let letterNum = 0;
  // let hasDigit = false;
  // let l = 0,
  //   r = 0;
  // let maxLen = -1;
  // // 遍历字符串中每个字符作为起点
  // while (l < str.length) {
  //   let letterCount = 0;
  //   // 从起点开始向右扩展子串
  //   while (r < str.length) {
  //     // 统计字母个数
  //     if (/[a-zA-Z]/.test(str[r])) {
  //       letterCount++;
  //     } else {
  //       hasDigit = true;
  //     }
  //     // 如果字母数量为1且当前子串长度大于最大长度,更新最大长度
  //     if (letterCount === 1 && r - l + 1 > maxLen && hasDigit) {
  //       maxLen = r - l + 1;
  //     }
  //     // 如果字母数量超过1,结束当前子串扩展
  //     if (letterCount > 1) {
  //       break;
  //     }

  //     r++;
  //   }

  //   // 重置右指针,左指针右移
  //   r = ++l;
  // }

  // console.log(maxLen);
  // 使用滑动窗口优化
  let l = 0,
    r = 0; // 定义左右指针
  let letterCount = 0; // 记录当前窗口内字母的数量
  let hasDigit = false; // 记录当前窗口是否包含数字
  let maxLen = -1; // 记录最大长度

  // 右指针向右移动扩展窗口
  while (r < str.length) {
    // 如果当前字符是字母,字母计数加1
    if (/[a-zA-Z]/.test(str[r])) {
      letterCount++;
    } else {
      // 如果是数字,标记hasDigit为true
      hasDigit = true;
    }

    // 当窗口内字母数量大于1时,需要收缩窗口
    while (letterCount > 1) {
      if (/[a-zA-Z]/.test(str[l])) {
        letterCount--;
      } else if (!/[a-zA-Z]/.test(str[l + 1])) {
        hasDigit = false;
      }
      l++;
    }

    // 更新最大长度
    if (letterCount === 1 && hasDigit) {
      maxLen = Math.max(maxLen, r - l + 1);
    }

    r++; // 右指针右移
  }

  console.log(maxLen);
})();