You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:20:28