[HAI] home work leetcode WIP
https://leetcode.com/problems/string-compression/submissions/1451041094/
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
// export function compress(chars: string[]) {
|
||||
// let L = 0;
|
||||
// let R = 1;
|
||||
// const N = chars.length;
|
||||
// let result = "";
|
||||
// let currentCounter = 1;
|
||||
|
||||
// while (L <= N && R <= N) {
|
||||
// const curL = chars[L];
|
||||
// const curR = chars[R];
|
||||
|
||||
|
||||
// if (curL !== curR || curR === undefined) {
|
||||
// result += curL;
|
||||
// if (currentCounter > 1) {
|
||||
// result += currentCounter;
|
||||
// currentCounter = 1;
|
||||
// }
|
||||
// L = R;
|
||||
// }
|
||||
|
||||
// if (curL === curR) {
|
||||
// currentCounter++;
|
||||
// }
|
||||
|
||||
// R++
|
||||
// }
|
||||
|
||||
// return result.length;
|
||||
// };
|
||||
|
||||
export function compress(chars: string[]) {
|
||||
let L = 0;
|
||||
let R = 1;
|
||||
const N = chars.length;
|
||||
let currentCounter = 1;
|
||||
|
||||
while (L <= N && R <= N) {
|
||||
const curL = chars[L];
|
||||
const curR = chars[R];
|
||||
|
||||
|
||||
if (curL !== curR || curR === undefined) {
|
||||
if (currentCounter > 1) {
|
||||
[...("" + currentCounter)].forEach((item, i) => {
|
||||
chars[L + 1 + i] = item;
|
||||
});
|
||||
currentCounter = 1;
|
||||
}
|
||||
L = R;
|
||||
}
|
||||
|
||||
if (curL === curR) {
|
||||
currentCounter++;
|
||||
chars[R] = "";
|
||||
}
|
||||
|
||||
R++
|
||||
}
|
||||
|
||||
for (let [key, value] of Object.entries(chars)) {
|
||||
if (value === "") {
|
||||
chars.splice(+key, 1)
|
||||
}
|
||||
}
|
||||
|
||||
console.log({ chars })
|
||||
|
||||
return chars.filter(item => item).length;
|
||||
};
|
||||
Reference in New Issue
Block a user