簡體   English   中英

誰能幫助我理解為什么我的 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

當我用測試運行它時,它再次工作/通過,當我提交它時,代碼失敗。 我不確定算法也試圖輸入什么輸入,但我認為它是一個空數組?

我知道我可以只查找答案,但我試圖在不查找的情況下完全解決問題。

//"上次執行的輸入[]"

如果查看 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 循環嘗試訪問未定義的空數組的第一個值的length

  • 輸入參數是[]splitWords初始值是[]
  • 然后splitWords !== undefined為真,
  • splitWords[0].length意思是([])[0].length ,顯然([])[0]是未定義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM