Valid Parentheses
題號:20
const leftBracket = {
"{": 1,
"[": 2,
"(": 3,
}
const rightBracket = {
"}": 1,
"]": 2,
")": 3,
}
var isValid = function(s) {
let waiting = []
for (let i = 0 ; i < s.length ; i++){
if (leftBracket[s[i]]){
waiting.push(leftBracket[s[i]])
continue
}
if (rightBracket[s[i]] !== waiting[waiting.length -1]) return false
waiting.pop()
}
return waiting.length === 0
}
var isValid = function(s) {
let length = s.length
while (length > 0 && s.length) {
s = s.replace(/\[\]|\{\}|\(\)/g, '')
length -= 2
}
return s === ''
}
Merge Two Sorted Lists
題號:21
var mergeTwoLists = function(list1, list2) {
let result = []
let head1 = list1
let head2 = list2
while (head1 || head2){
if (head1 && head2) {
if (head1.val <= head2.val){
result.push(head1.val)
head1 = head1.next
} else {
result.push(head2.val)
head2 = head2.next
}
continue
}
if (head1) {
result.push(head1.val)
head1 = head1.next
} else {
result.push(head2.val)
head2 = head2.next
}
}
return result.reduceRight((next, val)=>({next, val}), null)
}
Domino and Tromino Tiling
題號:790
let cheat = new Map([
[1, 1],
[2, 2],
[3, 5],
])
const modulo = 1e9 + 7
var numTilings = function(n) {
const counter = (m) => {
if (!cheat.get(m)) {
cheat.set(m, 2 * counter(m - 1) + counter(m - 3))
}
return cheat.get(m) % modulo
}
return counter(n)
}