标签:
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; } } }
标签:
原文地址:http://www.cnblogs.com/wenchan/p/5782325.html