[英]Program taking too much time
I'm trying to solve a coding problem, the problem is:我正在尝试解决编码问题,问题是:
This problem was authored by tunyash on Hackerrank with title 'Repeated String'此问题由 tunyash 在 Hackerrank 上以“重复字符串”为标题撰写
My current solution is taking too much time to run我当前的解决方案运行时间过长
This is what I am currently doing:这就是我目前正在做的事情:
I've made a function to do the counting as follows:我制作了一个 function 来进行计数,如下所示:
long long repeatedString(std::string s, long long n) {
long long sIndex{ 0 }, length = s.size(), result{ 0 };
for (long long i = 0; i < n; i++)
{
if (sIndex > (length - 1))
sIndex = 0;
if (s[sIndex] == 'a')
result += 1;
sIndex += 1;
}
return result;
}
I've tried modifying and using binary search algorithm by first writing the whole string then searching but the writing part takes too much time and seems not very intuitive我尝试通过首先编写整个字符串然后搜索来修改和使用二进制搜索算法,但是编写部分花费了太多时间并且看起来不是很直观
This is a typical beginner programming exercise.这是一个典型的初学者编程练习。 The idea is that you shouldn't blindly overengineer the problem, when a simple mathematical formula is right around the corner.这个想法是,当一个简单的数学公式指日可待时,你不应该盲目地过度设计问题。 In this case you can simply count the number of a
's in the original string and multiply it by n
to get the desired result:在这种情况下,您可以简单地计算原始字符串中a
的数量并将其乘以n
以获得所需的结果:
std::count(s.begin(), s.end(), 'a') * n
where s
is your input string.其中s
是您的输入字符串。
Edit: I misinterpreted the question.编辑:我误解了这个问题。 I assumed n
was the number of repetitions of the whole string, whereas it actually was the number of characters to concatenate by modularly concatenating the strings characters up until n
number of characters.我假设n
是整个字符串的重复次数,而实际上它是通过模块化连接字符串字符直到n
个字符来连接的字符数。 In this case, simply divide before multiplying: n / s.length()
and adjust for the n % s.length()
characters remaining with addition.在这种情况下,只需在相乘前除以: n / s.length()
并调整剩余的n % s.length()
字符。 I will leave this as an exercise.我将把它留作练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.