給定一個字元數組 char,使用以下演算法對其進行壓縮:
壓縮後的字串 s 不應單獨返回,而是儲存在輸入字元數組 chars 中。請注意,長度為 10 或更長的群組將被拆分為 chars 中的多個字元。
修改完輸入陣列後,傳回陣列的新長度。
您必須編寫一個僅使用恆定額外空間的演算法。
為了解決這個問題,我們需要迭代數組,同時追蹤當前字元及其計數。當遇到新字元時,我們將目前字元及其計數(如果大於 1)新增到陣列中。我們需要確保這樣做能夠滿足空間複雜度要求。
暴力解決方案涉及建立一個新數組來儲存輸入數組的壓縮版本。這不節省空間,但可以幫助我們理解所涉及的步驟。
function compressBruteForce(chars: string[]): number { const n = chars.length; let compressed: string[] = []; let i = 0; while (i < n) { let char = chars[i]; let count = 0; while (i < n && chars[i] === char) { i++; count++; } compressed.push(char); if (count > 1) { compressed.push(...count.toString().split('')); } } for (let j = 0; j < compressed.length; j++) { chars[j] = compressed[j]; } return compressed.length; }
暴力解決方案空間利用率不高,且不滿足僅使用恆定額外空間的限制。
最佳化的解決方案涉及修改輸入數組以儲存壓縮版本。我們使用兩個指標:一個用於讀取輸入數組,一個用於寫入壓縮輸出。
function compress(chars: string[]): number { let writeIndex = 0; let i = 0; while (i < chars.length) { let char = chars[i]; let count = 0; // Count the number of consecutive repeating characters while (i < chars.length && chars[i] === char) { i++; count++; } // Write the character chars[writeIndex] = char; writeIndex++; // Write the count if greater than 1 if (count > 1) { let countStr = count.toString(); for (let j = 0; j < countStr.length; j++) { chars[writeIndex] = countStr[j]; writeIndex++; } } } return writeIndex; }
console.log(compressBruteForce(["a","a","b","b","c","c","c"])); // 6, ["a","2","b","2","c","3"] console.log(compressBruteForce(["a"])); // 1, ["a"] console.log(compressBruteForce(["a","b","b","b","b","b","b","b","b","b","b","b","b"])); // 4, ["a","b","1","2"] console.log(compressBruteForce(["a","a","a","a","a","a","a","a","a","a"])); // 3, ["a","1","0"] console.log(compressBruteForce(["a","b","c"])); // 3, ["a","b","c"] console.log(compress(["a","a","b","b","c","c","c"])); // 6, ["a","2","b","2","c","3"] console.log(compress(["a"])); // 1, ["a"] console.log(compress(["a","b","b","b","b","b","b","b","b","b","b","b","b"])); // 4, ["a","b","1","2"] console.log(compress(["a","a","a","a","a","a","a","a","a","a"])); // 3, ["a","1","0"] console.log(compress(["a","b","c"])); // 3, ["a","b","c"]
字串運算:
就地演算法:
透過練習這些問題和策略,您可以提高解決問題的能力,並為各種編碼挑戰做好更好的準備。
以上是Typescript 編碼編年史:字串壓縮的詳細內容。更多資訊請關注PHP中文網其他相關文章!