谁能帮我理解为什么我的 leetcode 问题会出现这个运行时错误?最长前缀

Can anyone help me understand why im getting this runtime error with my leetcode problem? Longest Prefix

我正在为即将到来的面试练习 Leetcode 问题,我正在做最长的前缀 问题,当我 运行 带有预设的代码时,我通过了所有测试,但是当我提交要通过的代码时,我收到 运行 时间错误。这是我在下面写的代码。

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let splitWords = [];
    let commonPrefix =[];
    strs.forEach((word,i) =>{
        splitWords[i] = word.split('');
    })
    if( splitWords !== undefined || splitWords.length > 0){
    for(i=0; i < splitWords[0].length; i ++){
        if(splitWords[0][i] ==  splitWords[1][i] &&  splitWords[0][i] == splitWords[2][i]){
        
        commonPrefix.push(splitWords[0][i])
            console.log(commonPrefix)
         }else{
           break;
         }
        }
       }
  return (commonPrefix === undefined || commonPrefix.length == 0 ? commonPrefix = "" : commonPrefix.join(''))
};

这是我在提交时遇到的错误:

Line 12 in solution.js
    for(i=0; i < splitWords[0].length; i ++){
                               ^
TypeError: Cannot read property 'length' of undefined
    Line 12: Char 32 in solution.js (longestCommonPrefix)
    Line 33: Char 19 in solution.js (Object.<anonymous>)
    Line 16: Char 8 in runner.js (Object.runner)
    Line 24: Char 26 in solution.js (Object.<anonymous>)
    Line 1200: Char 30 in loader.js (Module._compile)
    Line 1220: Char 10 in loader.js (Object.Module._extensions..js)
    Line 1049: Char 32 in loader.js (Module.load)
    Line 937: Char 14 in loader.js (Function.Module._load)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    Line 17: Char 47 in run_main_module.js

当我用测试 运行 时,它再次执行 work/pass,当我提交它时,代码失败。我也不确定算法试图输入什么输入,但我认为它是一个空数组?

我知道我只能查找答案,但我试图在不查找的情况下完全解决问题。

//"最后执行的输入[]"

看一下Leetcode问题的约束条件,可以看到strs数组中有可能是空字符串

0 <= strs[i].length <= 200

例如你可以 Input: strs = ["","flow","flight"].

通过循环遍历 strs 数组的方式,拆分每个字符串并将它们添加到 splitWords 数组将导致以下结果:

0: []
1: (5) ["f", "l", "o", "w"]
2: (5) ["f", "l", "i", "g", "h", "t"]

不检查空字符串将导致您的 for-loop 尝试访问未定义的空数组第一个值的 length

  • 输入参数是[]splitWords初始值是[]
  • splitWords !== undefined为真,
  • splitWords[0].length的意思是([])[0].length,显然([])[0]是undefined.