Skip to content

Commit

Permalink
feat: add LeetCode
Browse files Browse the repository at this point in the history
  • Loading branch information
plskz committed Apr 12, 2023
1 parent 0539c38 commit c79f2ea
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
18 changes: 18 additions & 0 deletions LeetCode/removing-stars-from-a-string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function removeStars(s: string): string {
let stack: string[] = [];

for (let char of s) {
if (char !== '*') {
stack.push(char);
} else {
stack.pop();
}
}

return stack.join('');
}

console.log(removeStars('leet**cod*e'));
console.log(removeStars('erase*****'));

// TODO: add other approach
59 changes: 59 additions & 0 deletions LeetCode/simplify-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Solution 1
function simplifyPath(path: string): string {
let stack: string[] = [];
let ans: string = '';
let n = path.length;

for (let i = 0; i < n; i++) {
let dir = '';

while (i < n && path[i] !== '/') {
dir += path[i];
i++;
}

if (dir === '..') {
stack.pop();
} else if (dir === '.' || dir === '') {
continue;
} else {
stack.push(dir);
}
}

for (let dir of stack) {
ans += '/' + dir;
}

return ans || '/';
}

// Solution 2
function simplifyPath2(path: string): string {
const stack: string[] = [];
const dirs = path.split('/');

for (const dir of dirs) {
if (dir === '' || dir === '.') {
continue;
} else if (dir === '..') {
stack.pop();
} else {
stack.push(dir);
}
}

return '/' + stack.join('/');
}

// Solution 3
function simplifyPath3(path: string): string {
const stack: string[] = [];

for (const dir of path.split('/')) {
if (dir === '..') stack.pop();
else if (dir && dir !== '.') stack.push(dir);
}

return '/' + stack.join('/');
}

0 comments on commit c79f2ea

Please sign in to comment.