[HAI] GPT optimisation
https://leetcode.com/problems/string-compression/submissions/1451041094/main
parent
0ae89af862
commit
8e4c2c136e
@ -1,36 +1,64 @@
|
||||
export function compress(chars: string[]) {
|
||||
export function compress(chars: string[]): number {
|
||||
let L = 0;
|
||||
let R = 1;
|
||||
let count = 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] = " ";
|
||||
while (R <= N) {
|
||||
if (chars[R] !== chars[L]) {
|
||||
if (count > 1) {
|
||||
const countStr = count.toString();
|
||||
for (let i = 0; i < countStr.length; i++) {
|
||||
chars[++L] = countStr[i];
|
||||
}
|
||||
}
|
||||
L++;
|
||||
if (R < N) chars[L] = chars[R];
|
||||
count = 1;
|
||||
} else {
|
||||
count++;
|
||||
}
|
||||
|
||||
R++;
|
||||
}
|
||||
|
||||
for (let i = chars.length - 1; i >= 0; i--) {
|
||||
if (chars[i] === " ") {
|
||||
chars.splice(i, 1);
|
||||
}
|
||||
}
|
||||
chars.length = L;
|
||||
|
||||
return chars.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 i = chars.length - 1; i >= 0; i--) {
|
||||
// if (chars[i] === " ") {
|
||||
// chars.splice(i, 1);
|
||||
// }
|
||||
// }
|
||||
|
||||
// return chars.length;
|
||||
// }
|
||||
|
||||
Loading…
Reference in New Issue