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

LeetCode Valid Anagram代码本地正常但提交失败,求问题排查

问题:有效字母异位词代码提交LeetCode失败

我编写的有效字母异位词(Valid Anagram)代码在本地编辑器及在线编辑器测试示例均运行正常,但提交至LeetCode后仅通过24/38个测试用例。其中输入s="a"、t="a"时,代码返回false,而预期结果为true。

以下是我的代码:

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */

let readedIndices = []
function checkReadedIndices(indice){
    let res = false
    for(let i=0; i<readedIndices.length; i++){
        if(indice == readedIndices[i]){
            res = true
        }
    }
    return res
}

var isAnagram = function(s, t) {
    let result = false
    if(s.length !== t.length)
        return result
    for(let i=0; i < s.length; i++){
        for(let n=0; n < t.length; n++){
            if(s[i] === t[n]){
                if(checkReadedIndices(n) === false){
                    readedIndices.push(n)
                    break
                }
            }
        }
    }
    if(readedIndices.length === s.length)
        result = true

    return result
};
//console.log(isAnagram("a", "a"))

问题原因

核心问题在于全局变量readedIndices没有在每次调用isAnagram时重置。LeetCode会多次调用isAnagram函数验证不同测试用例,第一次调用后数组内的残留数据不会自动清空,后续测试用例会复用这个数组,导致判断逻辑出错。比如测试用例s="a"、t="a"如果不是第一个执行的用例,此时readedIndices可能已经存在之前测试留下的索引,当前用例无法正确将索引0加入数组,最终readedIndices.length不等于s.length,返回false。

修复方案

将readedIndices移到isAnagram函数内部,确保每次调用函数时都初始化空数组,让每个测试用例的判断独立。同时可以用数组的includes方法简化重复索引的判断逻辑。

修改后的代码

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    if(s.length !== t.length)
        return false
    let readedIndices = []
    for(let i=0; i < s.length; i++){
        let matched = false
        for(let n=0; n < t.length; n++){
            if(s[i] === t[n] && !readedIndices.includes(n)){
                readedIndices.push(n)
                matched = true
                break
            }
        }
        // 当前字符在t中找不到未匹配的位置,直接返回false
        if(!matched) return false
    }
    return true
};

更高效的实现思路

上面的嵌套循环时间复杂度为O(n²),长字符串场景下效率较低。可以用哈希表统计字符出现次数,时间复杂度优化为O(n):

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    if(s.length !== t.length) return false
    const count = {}
    for(const char of s){
        count[char] = (count[char] || 0) + 1
    }
    for(const char of t){
        if(!count[char]) return false
        count[char]--
    }
    return true
};

内容的提问来源于stack exchange,提问作者tom_so

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:05:21