[英]I am trying to solve this version of wildcard problem using typescript
我正在嘗試使用打字稿解決這個版本的通配符問題。 但是,我提供的一些測試用例沒有通過。 這是代碼如何工作的總結。
平衡字符串是字符串中每個字符與其他字符出現次數相等的字符串
例如,“ab”、“aaabbb”和“ababaabb”是平衡的,但“abb”和“abbaa”不是。
function balanced(s: string): boolean {
const MAX = 1000;
let wildcards: number = 0;
const map: { [key: string]: number } = {};
let characterCount = 0;
for (const char of s) {
if (char === '*') {
wildcards++;
} else {
if (!map[char]) {
map[char] = 0;
}
map[char]++;
if (map[char] > characterCount) {
characterCount = map[char];
}
}
}
const mapSize = Object.keys(map).length;
if (mapSize === MAX && characterCount === 1) {
return wildcards % MAX === 0;
}
if (mapSize < MAX && characterCount === 1 && wildcards <= (MAX - mapSize)) {
return true;
}
if (wildcards === s.length) {
return true;
}
for (const char in map) {
while (map[char] + 1 <= characterCount) {
map[char]++;
wildcards--;
}
if (wildcards < 0) return false;
}
if (wildcards % characterCount === 0) {
return true;
}
return false;
}
我正在針對以下輸入測試代碼
1: "a" should return true
2: "ab" should return true
3: "abc" should return true
4: "abcb" should return false
5: "Aaa" should return false
6: "abcb*" should return false
7: "abcb**" shoud return true
8: "***********" should return true
9: "" should return true
10: "abd*xdx*yba*" should return true
11: "aabb***" should return false
12: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" should return false
13: "JB**JTIT*****EY" should return false
12: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" should return false
不,它應該返回true
所有其他測試通過
https://stackblitz.com/edit/vitest-dev-vitest-afgmgj?file=balanced.test.ts&initialPath=__vitest_ _
我發現了類似的問題。 我只是稍微扭曲了解決方案。
const factorPairs = (n: number) =>
[...Array(Math.floor(Math.sqrt(n)))].map((_, i) => i + 1)
.flatMap(f => n % f == 0 ? [[f, n / f], [n / f, f]] : []);
const balanced = (s: string): boolean => {
if (!s) return true;
const ss = s.split('');
const chars = [...new Set(ss.filter(s => s !== '*'))];
const counts = ss.reduce(
(counts, s) => s === '*' ? counts : ((counts[s] += 1), counts),
Object.fromEntries(chars.map(l => [l, 0]))
);
const maxCount = Math.max(...Object.values(counts));
return factorPairs(ss.length).some(
([count, letters]) =>
letters <= 52 &&
letters >= chars.length &&
count >= maxCount
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.