Skip to content

Commit f239dfb

Browse files
authored
Merge pull request #495 from gitsunmin/main
[gitsunmin] Week 7 Solutions
2 parents b471b65 + 9236dc1 commit f239dfb

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* https://leetcode.com/problems/longest-substring-without-repeating-characters/
3+
* time complexity : O(n)
4+
* space complexity : O(n)
5+
*/
6+
function lengthOfLongestSubstring(s: string): number {
7+
let n = s.length, ans = 0;
8+
const map = new Map<string, number>();
9+
for (let j = 0, i = 0; j < n; j++) {
10+
if (map.has(s[j])) {
11+
i = Math.max((map.get(s[j]) ?? 0) + 1, i);
12+
}
13+
ans = Math.max(ans, j - i + 1);
14+
map.set(s[j], j);
15+
}
16+
return ans;
17+
};

reverse-linked-list/gitsunmin.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* https://leetcode.com/problems/reverse-linked-list
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
7+
class ListNode {
8+
val: number
9+
next: ListNode | null
10+
constructor(val?: number, next?: ListNode | null) {
11+
this.val = (val === undefined ? 0 : val)
12+
this.next = (next === undefined ? null : next)
13+
}
14+
}
15+
16+
/** Not used in real problem */
17+
const arrayToListNode = (arr: number[]): ListNode | null => {
18+
if (arr.length === 0) return null;
19+
let head = new ListNode(arr[0]);
20+
let curr = head;
21+
for (let i = 1; i < arr.length; i++) {
22+
curr.next = new ListNode(arr[i]);
23+
curr = curr.next;
24+
}
25+
return head;
26+
}
27+
28+
/* Main function */
29+
function reverseList(head: ListNode | null): ListNode | null {
30+
let prev: ListNode | null = null;
31+
let current = head;
32+
33+
while (current !== null) {
34+
const next = current.next;
35+
current.next = prev;
36+
prev = current;
37+
current = next;
38+
}
39+
40+
return prev;
41+
};
42+
43+
/* Examples */
44+
const input1 = [1, 2, 3, 4, 5];
45+
const input2 = [1, 2];
46+
const input3 = [];
47+
48+
console.log('output1:', reverseList(arrayToListNode(input1)));
49+
console.log('output2:', reverseList(arrayToListNode(input2)));
50+
console.log('output3:', reverseList(arrayToListNode(input3)));

0 commit comments

Comments
 (0)