ror*_*y-h 7 javascript algorithm
我正在 Hackerrank 中完成以下挑战之一:
\n\n\n\n\nLilah 有一个由小写英文字母组成的字符串 s,她重复了无数次。
\n\n给定一个整数 n,查找并打印 Lilah\xe2\x80\x99s 无限字符串的前 n 个字母中字母 a\xe2\x80\x99s 的数量。\n 第一行包含单个字符串 s。 \n 第二行包含一个整数 n。
\n
我需要打印一个整数,表示通过无限次重复 S 创建的无限字符串的前 N 个字母中字母 a\xe2\x80\x99s 的数量。
\n\n例如:
\n\n\n\n\ns 是 'aba', n = 10.. 无限字符串\n 的前 n = 10 个字母是 'abaabaabaa...' 因为有 7 个 a\xe2\x80\x99s,所以最终得到 7回答
\n
这就是我的答案。它通过了前两个案例,但未能通过其余的案例。
\n\nfunction repeatedString(s, n) {\n var repeat = Math.round(n / s.length);\n var remainder = n % s.length;\n var answer = 0;\n for (var i = 0; i < s.length; i++) {\n if (s.charAt(i) == 'a') {\n answer += repeat;\n if (i < remainder)\n answer++;\n }\n }\n return answer;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n如果有人可以看看这个并提出更好的解决方案,那就太好了。
\n//From a website i found it.
const as = s.split("").filter(c => c === "a").length;
const times = parseInt(n / s.length);
const rest = n % s.length;
const totalAs = times * as
+ s.slice(0, rest).split("").filter(c => c === "a").length
return totalAs;
Run Code Online (Sandbox Code Playgroud)
任何想要查看 HackerRank 上原始问题的人都可以在这里查看(也包含在下面)。问题陈述是:
n重复创建的无限字符串的第一个字母中字母 a 的数量。s这有两个部分。
s被“无限地”重复,但我们只需要检查到 length n。让我们先从简单的问题开始:编写一个函数来计算字符串中包含字符的次数。
String.prototype.countCharacter = function(char) {
return [...this].filter(c => c === char).length;
}
console.log('aaaa'.countCharacter('a')); // 4
console.log('aabb'.countCharacter('b')); // 2Run Code Online (Sandbox Code Playgroud)
现在这是棘手的部分。我们可以天真地使用String.repeat()重复字符串直到它的长度大于n,但是对于任意大的n,这变得不切实际。事实上,HackerRank 为我们提供了一个n大于最大字符串长度的测试用例,因此我们需要采取更高级别的方法。
我们知道字符串中有多少个 a s,这些 a 将被重复 - 如果我们重复m多次,我们将得到m * s.countCharacter('a')一个 a,其中m > (n/l)和l是s.length。这并不像看起来那么复杂:我们需要重复该字符串,直到得到长度大于 的字符串n,并且我们可以存储需要重复该字符串才能到达(或经过)的次数n一个名为 的变量repeatsRequired,它刚刚n / l被舍入。
从那里,很容易知道该字符串有多少个字符,并且我们可以知道末尾有多少个额外的charactersRequired % l字符。如果我们知道末尾有多少个多余的字符,我们可以将多余的部分切掉s并计算 a 的数量,a 的总数将是:
(number of a's in s) * (repeats required - 1)
+ (number of a's in final partial repeat)
Run Code Online (Sandbox Code Playgroud)
String.prototype.countCharacter = function(char) {
return [...this].filter(c => c === char).length;
}
// Complete the repeatedString function below.
function repeatedString(s, n) {
const l = s.length,
repeatsRequired = Math.ceil(n / l),
charsRequired = repeatsRequired * l,
numCharsInLastRepeat = l - (charsRequired % n);
const a_s = s.countCharacter('a'),
a_r = s.slice(0, numCharsInLastRepeat).countCharacter('a');
return a_s * (repeatsRequired - 1) + a_r;
}
console.log(repeatedString('aba', 10)); // 7
console.log(repeatedString('a', 1000000000000)); // 1000000000000Run Code Online (Sandbox Code Playgroud)
第一个错误是您的调用Math.round应该是Math.floor. 您可以验证代码是否正常工作,因为您的代码显示为repeatedString('cat', 2)2,而它应该显示为 1。
在再次提交之前,您应该手动运行几次健全性检查。
| 归档时间: |
|
| 查看次数: |
16530 次 |
| 最近记录: |