算法 - 将"内容" 更改为 「内容」

156 阅读1分钟

输入:哈好哒好哒"啊姐姐啊啥的'1231231'手机号"卡快快快kkllll“这是中文吧”看看快快快

输出:哈好哒好哒「啊姐姐啊啥的「1231231」手机号」卡快快快kkllll「这是中文吧」看看快快快

function formatQuotationMarks(str: string) {
    const code = [`"`, `'`];
    let list: string[] = [];
    let stack: string[] = [];
    let current;

    function pushStack(x: string) {
      stack.push(x);
      current = x;
    }
    function popStack() {
      stack.pop();
      current = stack[stack.length - 1];
    }

    for (let i = 0; i < str.length; i++) {
      let item = str[i];
      if (code.includes(item)) {
        if (current === item) {
          popStack();
          item = "」";
        } else {
          pushStack(item);
          item = "「";
        }
      }
      if (item === `“`) {
        item = "「";
      }
      if (item === `”`) {
        item = "」";
      }
      list.push(item);
    }
    return list.join("");
  }