Reverse String

来源:互联网 发布:mac键盘坏了怎么办 编辑:程序博客网 时间:2024/05/22 01:50

重新开始刷题吧!!!

Reverse String

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

Example:
Given s = “hello”, return “olleh”.


思路

这么简单,循环一遍不就行了,t[i] = s[length-i-1]
结果时间复杂度超了。。。。果然我还是想的太简单 too naive

所以换了个思路,就是只需要一半 t[i] = s[len-i-1],t[len-i-1]=s[i]
于是就纠结奇数偶数问题,要是奇数,中间那个数好像没有值
傻了简直,最开始t=s不就行了,不存在问题了


代码

class Solution {public:    string reverseString(string s) {        string t=s;  //没有赋值=s,下面的while中t不会取得值,记住!!        int len = s.size()-1;        int i=0;        while(i<=len)        {            t[i]=s[len];            t[len]=s[i];            i++;            len--;        }        return t;    }};
0 0
原创粉丝点击