如果不小心网友来到了这里请网友自动飘走,浪费你们时间表示歉意。该系列博客的目的是:想作为自律工具和朋友一起每天刷几道题作为打卡督促的功能,没有什么可参考学习的东西,也不是刷博客量充大佬的目的
题号:208
/**
* Initialize your data structure here.
*/
var Trie = function () {
//根节点
this.root = {}
};
/**
* Inserts a word into the trie.
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function (word) {
let curNode = this.root
for (let i = 0; i < word.length; i++) {
let letter = word[i]
if (!curNode[letter]) {
curNode[letter] = {}
}
curNode = curNode[letter]
}
curNode.isEnd = true
};
/**
* Returns if the word is in the trie.
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function (word) {
let curNode = this.root
for (let i = 0; i < word.length; i++) {
let letter = word[i]
if (curNode[letter]) {
curNode = curNode[letter]
} else {
return false
}
}
return curNode.isEnd ? true : false
};
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function (prefix) {
let curNode = this.root
for (let i = 0; i < prefix.length; i++) {
let letter = prefix[i]
if (curNode[letter]) {
curNode = curNode[letter]
} else {
return false
}
}
return true
};
题号:3
var lengthOfLongestSubstring = function (s) {
//滑动窗口,map记录是否重复
let map = new Map()
let left = 0, right = 0, max = 0
while (right < s.length) {
let letter = s[right]
if (map.has(letter)) {
let count = map.get(letter)
count++
map.set(letter, count)
} else {
max = Math.max(max, right - left + 1)
map.set(letter, 1)
}
if (map.get(letter) > 1) {
//收缩尾部使窗口字母满足题意
while (true) {
//收缩的过程中遇到count为1的从map中删除然后
//left + 1,遇到count为2的时候说明找到重复元素
//跳过该元素使count - 1
let count = map.get(s[left])
if (count == 2) {
count--
map.set(s[left], count)
left++
break
}
map.delete(s[left])
left++
}
}
right++
}
return max
};
题号:206
//递归反转
var reverseList = function (head) {
let helper = (node) => {
if (node == null) {
return null
}
let preNode = helper(node.next)
if (preNode == null) {
head = node
} else {
preNode.next = node
}
node.next = null
return node
}
helper(head)
return head
};
题号:15
var threeSum = function (nums) {
//升序排序
nums.sort((a, b) => {
return a - b
})
let result = []
for (let i = 0; i < nums.length; i++) {
//这里对a进行去重
if (i != 0 && nums[i] == nums[i - 1]) {
continue
}
const a = nums[i]
let left = i + 1, right = nums.length - 1
while (left < right) {
if (a + nums[left] + nums[right] > 0) {
right--
} else if (a + nums[left] + nums[right] < 0) {
left++
} else {
result.push([a, nums[left], nums[right]])
//这里对b进行去重
while (left < right) {
if (nums[left] == nums[left + 1]) {
left++
} else {
left++
break
}
}
//这里对c进行去重
while (right > left) {
if (nums[right] == nums[right - 1]) {
right--
} else {
right--
break
}
}
}
}
}
return result
};