JavaScript实现containRotations函数:判断字符串所有旋转是否在数组中
实现containRotations函数
实现思路
- 空字符串直接返回
true,满足题目规则 - 生成目标字符串的所有旋转结果:对于长度为
n的字符串,旋转i次(i从0到n-1)的结果为str.slice(i) + str.slice(0, i) - 将输入数组
arr转换为Set,利用其O(1)的查找效率提升性能 - 遍历所有旋转字符串,逐一检查是否存在于Set中,只要有一个不存在就返回
false,全部存在则返回true
代码实现
function containRotations(str, arr) { // 处理空字符串的特殊情况 if (str === '') { return true; } const strLength = str.length; // 转Set优化查找速度 const arrSet = new Set(arr); // 生成所有旋转串并检查 for (let i = 0; i < strLength; i++) { const rotation = str.slice(i) + str.slice(0, i); if (!arrSet.has(rotation)) { return false; } } return true; }
示例验证
// 空字符串场景 console.log(containRotations('', []) === true); // true // 非空串但数组为空场景 console.log(containRotations('abc', []) === false); // true // 所有旋转串都存在的场景 console.log(containRotations('stR!ng', ['stR!ng', 'gstR!n', 'ngstR!', '!ngstR', 'R!ngst', 'TwshnUh', 'tR!ngs']) === true); // true // 存在缺失旋转串的场景 console.log(containRotations('Word', ['Word', 'dWor', 'rdoW', 'DroW', 'rrWd']) === false); // true
内容的提问来源于stack exchange,提问作者Nicu Iorga
相关产品推荐
相关产品推荐

