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

LeetCode 344 Reverse String

时间:2016-08-18 00:55:54      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

1. 最近在练习Python,发现它的确有时候比较方便,比如这个,一行代码就解决了问题。

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]

注意到里面这个这个方法。This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

 

2. 此外,self在Python里面不是关键字,但是建议加上。There is no less verbose way. Always use self.x to access the instance attribute x. Note that unlike this in C++, self is not a keyword, though. You could give the first parameter of your method any name you want, but you are strongly advised to stick to the convention of calling it self.

 

3. 作为比较,把C#的解法也附上。可见语言之间的差别很大。

public class Solution {
    public string ReverseString(string s) 
    {
        if (s=="" || s.Length == 0) return s;
        
        char[] c = s.ToCharArray();
        SwapChar(c);
        return new string(c);
    }
    
    public static void SwapChar(char[] c) 
    {
        int left = 0, right = c.Length - 1;
        while (left < right) 
        {
            char temp = c[left];
            c[left] = c[right];
            c[right] = temp;
            ++left;
            --right;
        }
    }
}

 

LeetCode 344 Reverse String

标签:

原文地址:http://www.cnblogs.com/wenchan/p/5782325.html

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