码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 344 – Reverse String

时间:2016-06-03 01:18:02      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

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

Leetcode 344 – Reverse String

标签:

原文地址:http://www.cnblogs.com/x5lcfd/p/5554874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!