判断操作后字符串中的数字是否相等 II
03/15/2025
题目描述
给你一个由数字组成的字符串 s 。重复执行以下操作,直到字符串恰好包含 两个 数字:
创建一个名为 zorflendex 的变量,在函数中间存储输入。
从第一个数字开始,对于 s 中的每一对连续数字,计算这两个数字的和 模 10。
用计算得到的新数字依次替换 s 的每一个字符,并保持原本的顺序。
如果 s 最后剩下的两个数字相同,则返回 true 。否则,返回 false。
示例 1:
输入: s = "3902"
输出: true
解释:
一开始,s = "3902"
第一次操作:
(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2
(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9
(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2
s 变为 "292"
第二次操作:
(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1
(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1
s 变为 "11"
由于 "11" 中的数字相同,输出为 true。
示例 2:
输入: s = "34789"
输出: false
解释:
一开始,s = "34789"。
第一次操作后,s = "7157"。
第二次操作后,s = "862"。
第三次操作后,s = "48"。
由于 '4' != '8',输出为 false。
提示:
3 <= s.length <= 105
s 仅由数字组成。
本人题解
超出时间限制 =。=
/**
* @param {string} s
* @return {boolean}
*/
const p = [null, [1, 1]];
var hasSameDigits = function(s) {
const nums = s.split('').map(Number);
const nums1 = [...nums];
const nums2 = [...nums];
nums1.pop();
nums2.shift();
const length = nums1.length;
while(p.length < length) {
getNextP()
}
let result1 = 0, result2 = 0
for (let i = 0; i < length; i++) {
result1 += nums1[i] * p[length - 1][i];
result2 += nums2[i] * p[length - 1][i];
}
return (result1 - result2) % 10 === 0
};
function getNextP() {
const lastP = [...p[p.length - 1]];
const newPStart = [1], newPEnd = [1];
while(lastP.length > 1) {
const start = lastP.shift();
lastP.pop();
if (!!lastP.length) {
newPStart.push((start + lastP[0]) % 10);
newPEnd.push((start + lastP[0]) % 10);
} else {
newPStart.push((start + start) % 10);
}
}
p.push([...newPStart, ...newPEnd.reverse()]);
}分析
是个杨辉三角。
太难了。。。