LeetCode C++ 344. Reverse String【String】简单

    科技2025-09-15  46

    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"]

    题意:编写一个函数,其作用是将输入的字符串反转过来。要求必须原地修改输入数组、使用 O ( 1 ) O(1) O(1) 的额外空间解决这一问题。


    解法一 STL

    使用万能的STL大法:

    class Solution { public: void reverseString(vector<char>& s) { reverse(s.begin(), s.end()); } };

    效率如下:

    执行用时:56 ms, 在所有 C++ 提交中击败了68.97% 的用户 内存消耗:22.7 MB, 在所有 C++ 提交中击败了48.85% 的用户

    解法二

    很简单的代码:

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

    结果如下:

    执行用时:56 ms, 在所有 C++ 提交中击败了68.97% 的用户 内存消耗:22.8 MB, 在所有 C++ 提交中击败了37.87% 的用户
    Processed: 0.013, SQL: 8