[英]What is the difference between time complexity of string and char array declarations in c++?
In the question link , I first tried it using a character array.在问题链接中,我首先尝试使用字符数组。 This solution exceeded the time limit.此解决方案超出了时间限制。
char s[100000];
cin >> s;
int cnt[26];
for(int i=0;i<26;++i)
cnt[i]=0;
for(int i=0;i<strlen(s);++i)
cnt[s[i]-'a']++;
int count =0;
for(int i=0;i<26;++i)
if(cnt[i]>0)
count++;
cout << count << endl;
But then I changed the above code to this:但是后来我把上面的代码改成了这样:
string s;
cin >> s;
int cnt[26];
for(int i=0;i<26;++i)
cnt[i]=0;
for(int i=0;i<s.length();++i)
cnt[s.at(i)-'a']++;
int count =0;
for(int i=0;i<26;++i)
if(cnt[i]>0)
count++;
cout << count << endl;
And the code passed with ease.并且代码轻松通过。 And also the first one exceeded the time limit of 1 sec, while the second one passed with time of execution of 0.04 sec.而且第一个超过了1秒的时间限制,而第二个以0.04秒的执行时间过去了。 Why is there such a large difference in time of execution?为什么执行时间会有如此大的差异?
std::string
stores its length separately, so s.size()
is an instant operation. std::string
单独存储其长度,因此s.size()
是一个即时操作。
for(int i=0;i<strlen(s);++i)
calls strlen(s)
on every iteration, and strlen
loops through the entire string to the end to find the length of the string. for(int i=0;i<strlen(s);++i)
在每次迭代时调用strlen(s)
,并且strlen
循环遍历整个字符串直到最后找到字符串的长度。 So this innocent looking loop is actually O(n 2 ) complexity.所以这个看似无害的循环实际上是 O(n 2 ) 复杂度。
The C strings do not store length explicily, they just have a null atbthe end. C 字符串不明确存储长度,它们在末尾只有一个空值。 So to work out the length you need to iterate over the entire string character by character.因此,要计算出您需要逐个字符地遍历整个字符串的长度。 'sid::string::length' on the otherhand just returns the internally stored length.另一方面,'sid::string::length' 只返回内部存储的长度。
You can easily speed up the C version though, by caching the length in a variable before the loop and using the cached length in the for statement.不过,您可以通过在循环之前将长度缓存在变量中并在 for 语句中使用缓存的长度来轻松加速 C 版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.