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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
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/
.