use*_*670 -6 c algorithm optimization
我说没有strlen用于效率目的.因为如果你使用strlen那么你已经迭代了一个字符串,最好的算法总是迭代一个给定的容器不超过一次.所以帮助我思考如何实现一个功能
bool contains ( char * s1, char * s2 )
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
尝试:
bool contains ( char * s1, char * s2 )
{
// returns true or false depending on whether s1 is contained in s2
// define that every string contains the empty string
if ( !*s1 ) return true;
// search for substrings of s2 that equal s1
bool flag = true;
while ( *s2 )
{
char * c = s1;
while ( *c++ == *s2++ );
if ( !*c )
{
flag = true;
break;
}
else
{
flag = false;
}
}
return flag;
}
Run Code Online (Sandbox Code Playgroud)
但是,我想做几个优化
flag作为一个额外的内存字节else { flag = false; }是一个大部分时间进入的条件块,并且每次进入都会做同样的事情,所以我想以某种方式摆脱它if ( !*s1 ) return true;早期休息有助于更优雅地编写函数的其余部分,但我讨厌在函数开头检查"一个特殊情况"条件.如果可能的话,我希望该函数能够直接进入包含所有逻辑的单个循环.
char * c = *s1在循环的每次迭代副本是一个额外的字节,这将是很好的摆脱,但我不知道如何摆脱它我会写这个吗?
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |