LeetCode Reverse String

LeetCode Reverse String Write a function that takes a string as input and returns the string reversed. Example: Given s = “hello”, return “olleh”.


本题要把一个字符串逆序一下。最简单的题了,两种方法,一种是直接调用STL的reverse函数;另一种方法是用首尾指针不断swap。 方法1代码如下: [cpp] class Solution { public: string reverseString(string s) { reverse(s.begin(), s.end()); return s; } }; [/cpp] 本代码提交AC,用时9MS。 方法2代码如下: [cpp] class Solution { public: string reverseString(string s) { int i = 0, j = s.size() – 1; while (i < j) { swap(s[i], s[j]); ++i; –j; } return s; } }; [/cpp] 本代码提交AC,用时也是9MS。]]>

1 thought on “LeetCode Reverse String

  1. Pingback: LeetCode Reverse String II | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *