xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

leetcode 字符串的排列组合算法题解 All In One

leetcode 字符串的排列组合算法题解 All In One

js 实现字符串的全排列

const getFullPermutation = (str: string): string[] => {
  if (str.length === 1) {
    return [str];
  } else {
    const result = [];
    //遍历每一项
    for (let i = 0; i < str.length; i++) {
      // 当前的元素
      let current = str[i];
      // 其他元素
      let others = str.slice(0, i) + str.slice(i + 1);
      // 其他元素的全排列, 递归
      let temp = getFullPermutation(others);
      // 组合
      for (let j = 0; j < temp.length; j++) {
        const item = current + temp[j];
        result.push(item);
      }
    }
    return result;
  } 
}

// test
const str = `abc`;
getFullPermutation(str);


function getFullPermutation(str) {
  if (str.length === 1) {
    return [str];
  } else {
    const result = [];
    //遍历每一项
    for (let i = 0; i < str.length; i++) {
      // 当前的元素
      let current = str[i];
      // 其他元素
      let others = str.slice(0, i) + str.slice(i + 1);
      // 其他元素的全排列, 递归
      let temp = getFullPermutation(others);
      // 组合
      for (let j = 0; j < temp.length; j++) {
        const item = current + temp[j];
        result.push(item);
      }
    }
    return result;
  } 
}

// test
const str = `abc`;
getFullPermutation(str);


LeetCode 567. Permutation in String

LeetCode 567. 字符串的排列


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-08-06
 * @modified
 *
 * @description 567. Permutation in String
 * @description 567. 字符串的排列
 * @difficulty Medium
 * @time_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/permutation-in-string/
 * @link https://leetcode-cn.com/problems/permutation-in-string/
 * @solutions
 *
 * @best_solutions
 *
 */


export {};

const log = console.log;

// s1 和 s2 仅包含小写字母
function checkInclusion(s1: string, s2: string): boolean {
  const len1 = s1.length;
  const len2 = s2.length;
  // 如果 s1 长度大于 s2, 直接返回 false
  if (len1 > len2) {
    return false;
  }
  // 构造 a-z 26 个小写字母的集合
  // const count = Array(26).fill(0);
  count = [...new Uint8Array(26)];
  // const count = [...``.padEnd(26, 0)].map(i => 0);
  // const count = [...``.padEnd(26, 0)].map(Number);
  // 统计 a-z 26 个小写字母中,每个字母分别出现的次数
  for (let i = 0; i < len1; i++) {
    // 一个加
    count[s1.charCodeAt(i) - 97]++;
    //一个减
    count[s2.charCodeAt(i) - 97]--;
  }
  // 如果一加一减全部消除掉,s1 中每个出现的字母都为 0, 直接返回 true
  if (count.every(i => i === 0)) {
    return true;
  }
  // if (!count.some(i => i !== 0)) {
  //   return true;
  // }
  // s2 > s1, 继续遍历 s2 剩余的字母字符
  for (let i = len1; i < len2; i++) {
    // 先减一
    count[s2.charCodeAt(i) - 97]--;
    // 后加一, ??? 从 0 开始加 ???
    count[s2.charCodeAt(i - len1) - 97]++;
    // 如果一加一减全部消除掉,s1 中每个出现的字母都为 0, 直接返回 true
    if (count.every(i => i === 0)) {
      return true;
    }
    // if (!count.some(e => e !== 0)) {
    //   return true;
    // }
  }
  return false;
};

/*

s1 = `abcd`
s2 = `fghijk`

checkInclusion(s1, s2);
// false

*/



// 测试用例 test cases
const testCases = [
  {
    inputs: ['prosperity', 'properties'],
    result: false,
    desc: 'value equal to false',
  },
  {
    inputs: ['abcd', 'fghijk'],
    result: false,
    desc: 'value equal to false',
  },
  {
    inputs: ['abc', 'abcd'],
    result: true,
    desc: 'value equal to false',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const [input1, input2] = testCase.inputs;
  const result = checkInclusion(input1, input2);
  log(`test case ${i} result: `, result === testCase.result ? `✅ passed` : `❌ failed`, result);
  // log(`test case ${i} =`, testCase);
}

/*


error TS2550: Property 'fill' does not exist on type 'any[]'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2015' or later.

error TS2550: Property 'entries' does not exist on type '{ inputs: string[]; result: boolean; desc: string; }[]'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2015' or later.


*/

/*
function checkInclusion(s1: string, s2: string): boolean {
  if(s1.length > s2.length) {
    return false;
  }
  // 1. 获取 s1 的所有排列 set1
  const arr = getFullPermutation(s1);
  // 2. 遍历 set1, 判断 s2 中是否存在至少一个 s1 的排列
  for(let item of arr) {
    if(s2.includes(item)) {
      return true;
    }
  }
  return false;
};

function getFullPermutation(str: string): string[] {
  if (str.length === 1) {
    return [str];
  } else {
    const result = [];
    //遍历每一项
    for (let i = 0; i < str.length; i++) {
      // 当前的元素
      let current = str[i];
      // 其他元素
      let others = str.slice(0, i) + str.slice(i + 1);
      // 其他元素的全排列
      let temp = getFullPermutation(others);
      // 组合
      for (let j = 0; j < temp.length; j++) {
        const item = current + temp[j];
        result.push(item);
      }
    }
    return result;
  }
}

*/



https://leetcode.com/problems/permutation-in-string/
https://leetcode.cn/problems/permutation-in-string/

LeetCode 46. Permutations

Medium

LeetCode 46. 全排列

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-08-07
 * @modified
 *
 * @description 46. Permutations
 * @description 46. 全排列
 * @difficulty Medium
 * @time_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/permutations/
 * @link https://leetcode-cn.com/problems/permutations/
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

function permute(nums: number[]): number[][] {
  // 不同的整数
  if (nums.length === 1) {
    return [nums];
  } else {
    const result: number[][] = [];
    //遍历每一项
    for (let i = 0; i < nums.length; i++) {
      // 当前的元素
      const current = nums[i];
      // 其他元素
      const others = [...nums.slice(0, i), ...nums.slice(i + 1)];
      // 其他元素的全排列
      const temp = permute(others);
      // 组合
      for (let j = 0; j < temp.length; j++) {
        const item: number[] = [current, ...temp[j]];
        result.push(item);
      }
    }
    return result;
  }
};

interface TestCase {
  input: number[];
  result: number[][];
  desc: string;
}
// 测试用例 test cases
const testCases: TestCase[] = [
  {
    input: [1,2,3],
    result: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]],
    desc: 'value equal to [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]',
  },
];

for (const [i, testCase] of testCases.entries()) {
  // console.log(`testCase.input =`, testCase.input, typeof testCase.input);
  const result = permute(testCase.input);
  log(`test case ${i} result: `, JSON.stringify(result) === JSON.stringify(testCase.result) ? `✅ passed` : `❌ failed`, result);
  // log(`test case ${i} result: `, result === testCase.result ? `✅ passed` : `❌ failed`, result);
  // log(`test case ${i} =`, testCase);
}


export {};

// export {}; 必须注释掉 export, 才能运行 ts-node ✅
// npx ts-node ./046\ permutations.ts

https://leetcode.com/problems/permutations/

https://leetcode.cn/problems/permutations/

LeetCode 76. Minimum Window Substring

Hard

LeetCode 76. 最小覆盖子串


https://leetcode.com/problems/minimum-window-substring/
https://leetcode.cn/problems/minimum-window-substring/

题解视频

refs

https://www.cnblogs.com/xgqfrms/p/16389706.html



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-08-06 16:38  xgqfrms  阅读(82)  评论(4编辑  收藏  举报