如果不小心网友来到了这里请网友自动飘走,浪费你们时间表示歉意。该系列博客的目的是:想作为自律工具和朋友一起每天刷几道题作为打卡督促的功能,没有什么可参考学习的东西,也不是刷博客量充大佬的目的
题号:91
var numDecodings = function (s) {
let map = new Map()
for (let i = 0; i < 26; i++) {
map.set(`${i + 1}`, String.fromCharCode(65 + i))
}
//动态规划table的含义:数组下表i表示从0到第i个字符的时候的编码总数
let table = new Array(s.length + 1).fill(0)
for (let i = 0; i < table.length; i++) {
if (i == 0) {
table[i] = 0
} else if (i == 1) {
if (map.has(s[i - 1])) {
table[i] = 1
}
} else {
//判断条件只判断当前字符,当前和前一个字符组合,当前和前前一个字符组合...很多
//但是题目隐形有个条件,不能大于2个字符的组合,如果大于2的话首尾如果不为0那么
//组成的数字字符是不能映射为任何字母的,A到Z就是1到26在100以内的数字
let letter = s[i - 1]
let preletter = s[i - 2]
let count = 0
if (map.has(letter)) {
count += table[i - 1]
}
if (preletter !== '0' && map.has(preletter + letter)) {
if (i - 2 == 0) {
count += 1
} else {
count += table[i - 2]
}
}
table[i] = count
}
}
return table.pop()
};
题号:304
var NumMatrix = function (matrix) {
//初始化前缀和
//前缀和数组下标一般从下标1开始但是也不一定这样,这样处理方便后面计算差值
this.sums = new Array(matrix.length + 1)
for (let i = 0; i < this.sums.length; i++) {
let arr = new Array(matrix[0].length + 1).fill(0)
this.sums[i] = arr
}
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
this.sums[i + 1][j + 1] = this.sums[i][j + 1] + this.sums[i + 1][j] - this.sums[i][j] + matrix[i][j]
}
}
};
NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) {
return this.sums[row2 + 1][col2 + 1] - this.sums[row1][col2 + 1] - this.sums[row2 + 1][col1] + this.sums[row1][col1]
};
题号:303
var NumArray = function (nums) {
this.sums = new Array(nums.length + 1).fill(0)
for (let i = 0; i < nums.length; i++) {
this.sums[i + 1] = this.sums[i] + nums[i]
}
};
NumArray.prototype.sumRange = function (left, right) {
return this.sums[right + 1] - this.sums[left]
};