[leetcode]344. Reverse String

[leetcode]344. Reverse String


Analysis

周五啦,端午小长假要开始啦~—— [嘻嘻~]

Write a function that takes a string as input and returns the string reversed.
反转string

Implement

方法一:(space complexity O(N))

class Solution {
public:
    string reverseString(string s) {
        string s1 = "";
        int len = s.length();
        for(int i=len-1; i>=0; i--)
            s1 += s[i];
        return s1;
    }
};

方法二:(space complexity O(1))

class Solution {
public:
    string reverseString(string s) {
        int i, j;
        int len = s.length();
        i = 0;
        j = len-1;
        while(i<j){
            char t = s[i];
            s[i] = s[j];
            s[j] = t;
            i++;
            j--;
        }
        return s;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/80706558