这个代码测试的时候超时,能帮忙分析一下原因么?九度检测最后一个测试用例超时。
/************************************************************************/
/* 请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 */
/************************************************************************/
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
getline(cin, s);
size_t found = s.find(" ");
while (found != string::npos)
{
s.replace(found, 1, "%20");
found = s.find(" ");
}
cout << s;
}
Your algorithm is logically correct, but the time complexity is
O(N^2)
, and it will time out forN > 10000
strings.An algorithm that can be improved to linear time complexity.
I changed it:
http://ac.jobdu.com/problem.php?pid=1510 20ms AC
If there is really no library function...(it is better to use library functions)
Although the above writing method is long and looks laborious, it has better performance; but it is definitely not optimal, because the detection of strlen and spaces can be combined; in addition, if you are not sure that src is four-byte aligned, Additional checks should be done on the first few misaligned bytes.
Counting first mainly avoids the overhead of multiple dynamic memory allocations. If the string is not outrageously large, counting is very fast due to caching; each time an INT is detected, it is very fast to do 4 bit checks on it. , because all 4 tests are performed in registers.
However, this kind of optimization is only a suggestion (it also shows the power of C/C++); for real optimization, various details are required, such as unrolling a loop determined to be 4 times, etc. Therefore , use the library as much as possible, it is your best choice. I remember that there is a replace in JAVA's String? .
The complexity of yours is too high. The
s.find(" ")
in the loop is already the complexity ofO(n)
. This question can be completed by traversing + replacing once. It means looping once and encountering a space once. Just replace it, write it down roughly, see if you can pass it?The code of the questioner only needs to be modified in one place:
Regular match a space s