Follow

KMP算法实现字符串匹配和替换,JS ver.

class Solution {
  public static matchTable(str: string) {
    const strLen = str.length;
    const table: number[] = [];
    for (let pos = 0; pos < strLen; pos++) {
      let prefix: string[] = [];
      let suffix: string[] = [];
      for (let cursor = 0; cursor <= pos; cursor++) {
        prefix.push(str.slice(0, cursor));
        suffix.push(str.slice(cursor + 1, pos + 1));
      }
      prefix = prefix.filter((s) => s);
      suffix = suffix.filter((s) => s);
      const match: string[] = [""];
      prefix.forEach((pf) => {
        suffix.forEach((sf) => {
          if (pf === sf) {
            match.push(pf);
          }
        });
      });
      table.push(Math.max(...match.map((s) => s.length)));
    }
    return table;
  }

  public static matchString(target: string, search: string): number {
    const matchTable = this.matchTable(search);
    const targetLen = target.length;
    const searchLen = search.length;
    if (targetLen < searchLen) return -1;
    let pos = 0;
    while (pos <= targetLen - searchLen) {
      for (let cursor = 0; cursor < searchLen; cursor++) {
        if (target[pos + cursor] === search[cursor]) {
          if (cursor === searchLen - 1) {
            return pos;
          } else {
            continue; // for
          }
        } else {
          pos += cursor + 1 - matchTable[cursor];
          break; // for
        }
      }
    }
    return -1;
  }

  public static replace(A = "hello world", B = "hello", C = "Mars") {
    const lenA = A.length;
    const lenB = B.length;
    let res = A;
    const pos = this.matchString(res, B);
    if (pos >= 0) {
      res = res.slice(0, pos) + C + res.slice(pos + lenB, lenA);
      return res;
    } else {
      this.replace(res, B, C);
    }
    return res;
  }
}

console.log(Solution.replace("hello world", "world", "mars"));
· · Web · 0 · 1 · 1
Sign in to participate in the conversation
小森林

每个人都有属于自己的一片森林,也许我们从来不曾走过,但它一直在那里,总会在那里。迷失的人迷失了,相逢的人会再相逢。愿这里,成为属于你的小森林。