1805.字符串中不同整数的数目(javascript)1805.NumberofDifferentIntegersinaString
原创给你一根绳子 word 字符串由数字和小写字母组成。
请用空格替换每个非数字字符。例如,“a123bc34d8ef34” 将会变成 " 123 34 8 34" 。请注意,这些整数的其余部分是(彼此相邻,由至少一个空格分隔):“123”、“34”、“8” 和 “34” 。
返回对 word 更换完成后形成 不同 整数的数量。
仅当两个整数 无前导零 的十进制表示不同, 认为这两个整数也是不同的。
You are given a string word that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, “a123bc34d8ef34” will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: “123”, “34”, “8”, and “34”.
Return the number of different integers after performing the replacement operations on word.
Two integers are considered different if their decimal representations without any leading zeros are different.
示例 1:
输入:word = "a123bc34d8ef34"
输出:3
说明:不同的整数有 "123"、"34" 和 "8" 。注意,"34" 只计数一次。
示例 2:
输入:word = "leet1234code234"
输出:2
示例 3:
输入:word = "a1b01c001"
输出:1
解释:"1"、"01" 和 "001" 将其视为同一整数的十进制表示,因为比较十进制值时忽略前导零的存在。
提示:
- 1 <= word.length <= 1000
- word 由数字和小写字母组成
官方解决问题的思路:
对于每个字符串的整数部分,使用指针 left , 指向整数部分第一个字符的指针 right指向整数部分最后一个字符的下一个位置。为了删除前导零,如果 right−left >1 且 word[left]=‘0’我们将 left 向前移动一点,我。left =left +1。将区间 [left ,right)将相应的字符串插入哈希集,最终字符串中不同整数的数量等于哈希集的元素数量。
var numDifferentIntegers = function (word) {
const set = new Set()
let len = word.length,
left = 0,
right;
while (true) {
while (left < len && !isDigit(word[left])) {
left++
}
if (left === len) {
break;
}
right = left
while (right < len && isDigit(word[right])) {
right++
}
while (right - left > 1 && word[left] === 0) {
left++
}
set.add(word.slice(left, right));
left = right
}
return set.size
};
const isDigit = (ch) => {
return 0 <= ch && ch <= 9;
}
leetcode: https://leetcode.cn/problems/number-of-different-integers-in-a-string/description/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除