-
- 罗马数字转整数
- 409.最长回文串
-
- 字符串相加
- 594.最长和谐子序列
13. 罗马数字转整数
var romanToInt = function (s) {
const map = {
I: 1,
IV: 4,
V: 5,
IX: 9,
X: 10,
XL: 40,
L: 50,
XC: 90,
C: 100,
CD: 400,
D: 500,
CM: 900,
M: 1000,
};
let ans = 0;
for (let i = 0; i < s.length; i++) {
const substr = s.substring(i, i + 2);
if (i + 1 < s.length && map[substr]) {
ans += map[substr];
i += 1;
} else {
ans += map[s[i]];
}
}
return ans;
};
romanToInt("MCMXCIV");
409.最长回文串
var longestPalindrome = function (s) {
const map = {};
for (let ch of s) {
map[ch] = (map[ch] ?? 0) + 1;
}
let deleteCount = 0;
for (let key in map) {
if (map[key] % 2 !== 0) {
deleteCount += 1;
}
}
const ans = deleteCount > 1 ? s.length - (deleteCount - 1) : s.length;
return ans;
};
longestPalindrome("abccccdd");
415. 字符串相加
var addStrings = function (num1, num2) {
let i = num1.length - 1;
let j = num2.length - 1;
let carry = 0;
const res = [];
while (i >= 0 || j >= 0 || carry !== 0) {
let c1 = i >= 0 ? num1.charAt(i) - "0" : 0;
let c2 = j >= 0 ? num2.charAt(j) - "0" : 0;
const sum = c1 + c2 + carry;
res.push(sum % 10);
carry = Math.floor(sum / 10);
i--;
j--;
}
return res.reverse().join("");
};
addStrings("11", "123");
594.最长和谐子序列
var findLHS = function (nums) {
const map = new Map();
for (let ch of nums) {
map.set(ch, (map.get(ch) ?? 0) + 1);
}
console.log(map);
let max = 0;
for (let key of map.keys()) {
if (map.get(key + 1)) {
max = Math.max(max, map.get(key) + map.get(key + 1));
}
}
console.log(max);
return max;
};
findLHS([1, 3, 2, 2, 5, 2, 3, 7]);