LeetCode_344_Reverse String

题目描述:写一个函数用来翻转字符串,输入的字符串是一个给定的字符序列,不要使用额外的存储空间,你只能在原地修改字符串,空间复杂度为O(1),你可以假定所有的字符都是可以打印的ASCII字符。

Example1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Examp2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

思想:将字符串对折,前后对称的位置进行交换即可

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

实际运行是时间图
时间复杂度O(n),空间复杂度O(1)

猜你喜欢

转载自blog.csdn.net/all_about_WZY/article/details/88084791