String str;
cin>>str;
for(int i=0;i<str.length();i++){
....
}
if str.length()=n, then the total complexity of the algorithm is n*n?? or just n?
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
String str;
cin>>str;
for(int i=0;i<str.length();i++){
....
}
if str.length()=n, then the total complexity of the algorithm is n*n?? or just n?
Name |
---|
Both string::size and string::length are synonyms and return the exact same value. Complexity : O(1).
thanks...
Here is the C program to find length of string.
Thanks my friend...
Most modern compilers do an optimization with the function call being repeated without any changes, so instead it memorizes the value returned by that function, but still can not rely on compiler to do that and it's better to do it manually as the following:
for(int i=0, length=str.length(); i<length; ++i){
// your code
}
the code above runs in O(n) complexity instead of O(n^2), and it would be remarkable that the code runs faster for large strings lengths.
This is true for
strlen()
but not forstring::length()
, because the former is O(n) and the latter is O(1).well i always store the length in a separate variable before the loop, but a friend told me that the complexity of length() is O(n) so i wanted to make sure about the information, thanks for the help :)
The complexity for
string::size()/length()
is constant but of course it would be faster to store size in a variable (e.g.sz
) because of:-Accessing (
sz
) is faster than accessing (string::size()/length()
)-Comparing int(
i
) to int(sz
) is faster than comparing int(i
) to unsigned int(string::size()/length()
)read here http://www.cplusplus.com/reference/string/string/size/
read here https://seanhamptoncole.wordpress.com/2012/11/15/how-to-stop-being-stupid-in-10-easy-steps/
.