算法题题解记录——7. 创意标题匹配问题

170 阅读1分钟

题目

www.marscode.cn/practice/r3…

image.png

思路

此题关键点在于模板解析固定字符按顺序出现,注意处理首尾为通配符{}的边界情况。

固定字符要想保证顺序出现,可以通过匹配当前固定字符串,找到就让指针跳到匹配位置的后一位

代码

  1. 首先先写出solution的代码框架:
function solution(n, template_, titles) {
  // 模板解析
  let tArr = transferArr(template_);
  const ans = [];
  for (let i = 0; i < titles.length; i++) {
    ans.push(singleSolution(tArr, titles[i]));
  }
  return ans.join(',');
}

  1. 实现transferArr函数, 将ad{xyz}cdc{y}f{x}e转成 ['ad', 'cdc', 'f', ''e]
function transferArr(template_) {
  const tArr = []
  let a = template_.split('{')
  tArr.push(a[0])
  let b = a[1].split('}')
  for (let i = 1; i < a.length; i++) {
    tArr.push(a[i].split('}')[1])
  }
  return tArr
}
  1. 最后实现singleSolution 的单个判断:
function singleSolution(arr, title) {
  for (let i = 0; i < arr.length; i++) {
    if (i === 0 && arr[i] === '') {
      continue;
    }
    if (i === arr.length - 1 && !title.endsWith(arr[i])) {
      return 'False';
    }

    let j = title.indexOf(arr[i]);
    if (j !== -1) {
      // 匹配当前固定字符串,找到就让指针跳到匹配位置的后一位
      title = title.slice(j + arr[i].length);
    } else {
      return 'False';
    }
  }
  return 'True';
}

复杂度

  • 时间复杂度:O(nmt)O(n * m * t),其中m为通配符个数+1, t为标题的字符串长度

  • 空间复杂度:O(n)O(n)