Skip to content

Commit

Permalink
187th Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Aug 4, 2024
1 parent 264b647 commit 4224cba
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,11 @@ Ace Coding Interview with 75 Qs
| ---------------------------------- | ---------------- | ------ |
| 2390. Removing Stars From a String | [Solution][2390] | Medium |
| 735. Asteroid Collision | [Solution][735] | Medium |
| 394. Decode String | Solution | Medium |
| 394. Decode String | [Solution][394] | Medium |

[2390]: ./src/page-22/2390.%20Removing%20Stars%20From%20a%20String/removeStars.ts
[735]: ./src/page-7/735.%20Asteroid%20Collision/asteroidCollision.ts
[394]: ./src/page-4/394.%20Decode%20String/decodeString.ts

| Queue | | |
| --------------------------- | -------- | ------ |
Expand Down
9 changes: 9 additions & 0 deletions src/page-4/394. Decode String/decodeString.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { decodeString } from './decodeString';

describe('394. Decode String', () => {
test('decodeString', () => {
expect(decodeString('3[a]2[bc]')).toBe('aaabcbc');
expect(decodeString('3[a2[c]]')).toBe('accaccacc');
expect(decodeString('2[abc]3[cd]ef')).toBe('abcabccdcdcdef');
});
});
36 changes: 36 additions & 0 deletions src/page-4/394. Decode String/decodeString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
type DecodeString = (s: string) => string;

/**
* Accepted
*/
export const decodeString: DecodeString = (s) => {
const countStack: number[] = []; // Stack to store repeat counts
const stringStack: string[] = []; // Stack to store intermediate strings

let currentNum = 0; // Current number being processed
let currentString = ''; // Current string being processed

for (const char of s) {
if (!Number.isNaN(Number(char))) {
// If the character is a digit, update currentNum
currentNum = currentNum * 10 + Number(char);
} else if (char === '[') {
// If the character is '[', push currentNum and currentString to stacks
countStack.push(currentNum);
stringStack.push(currentString);
currentNum = 0; // Reset currentNum
currentString = ''; // Reset currentString
} else if (char === ']') {
// If the character is ']', pop from stacks and update currentString
const repeatTimes = countStack.pop(); // Get the last count
const lastString = stringStack.pop(); // Get the last string
currentString = lastString + currentString.repeat(repeatTimes || 1); // Repeat currentString and append
} else {
// If the character is a letter, append it to currentString
currentString += char;
}
}

// Return the fully decoded string
return currentString;
};

0 comments on commit 4224cba

Please sign in to comment.