MENU

LeetCode344. Reverse String(模拟)

2019 年 02 月 04 日 • 阅读: 1100 • LeetCode阅读设置

LeetCode344. Reverse String(模拟)

  • Easy
  • Accepted:356,200
  • Submissions:569,101

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

链接

https://leetcode.com/problems/reverse-string/

题意

翻转一个字符串,保证$O(1)$的空间复杂度。

题解

  • 嗯...试了下STL的reverse()函数
  • 直接一遍循环就好了,时间复杂度$O(n)$,空间复杂度$O(1)$

代码

  • Runtime: 24 ms, faster than 99.20% of C++ online submissions for Reverse String.
  • Memory Usage: 2.7 MB, less than 3.45% of C++ online submissions for Reverse String.
class Solution {
public:
    void reverseString(vector<char>& s) {
        reverse(s.begin(), s.end());
    }
};
// Accepted    24 ms 2.7 MB

class Solution {
public:
    void reverseString(vector<char>& s) {
        int len = s.size();
        for (int i = 0; i < len / 2; ++i)
            swap(s[i], s[len-1-i]);
    }
};

The end.
2019年2月4日 星期一