标签:
Solution 1:
class Solution {
public:
std::string reverseString( std::string s )
{
size_t halfLen = s.size() / 2;
for( size_t i = 0; i < halfLen; i++ )
{
std::swap( s.at( i ), s.at( s.size() - i - 1 ) );
}
return s;
}
};
6.09%
Solution 2:
class Solution {
public:
std::string reverseString( std::string s )
{
char* src = const_cast<char*>( s.c_str() );
char t, *d = &( src[s.size() - 1] );
while( d > src )
{
t = *src;
*src++ = *d;
*d-- = t;
}
return s;
}
};
29.33%,由上面的 16 ms –> 14ms
Solution 3: 用C,时间肯定快,四百多个testcase 4ms,但是还是只能beats 18%,不开心
char* reverseString( char* s )
{
char* h = s;
char t, *d = s + strlen(s) - 1;
while( d > h )
{
t = *h;
*h++ = *d;
*d-- = t;
}
return s;
}
其他:
1. const_cast<char*>
In particular, only const_cast may be used to cast away (remove) constness or volatility. Pointers to functions and pointers to member functions are not subject to const_cast
2. Visual Studio 写 c 要注意,默认还是 C++,最好直接用 cl
标签:
原文地址:http://www.cnblogs.com/x5lcfd/p/5554874.html