题解 | #反转字符串#

反转字符串

http://www.nowcoder.com/practice/c3a6afee325e472386a1c4eb1ef987f3

首尾交换,直到中间下标处

class Solution {
public:
    string solve(string str) {
        int len = str.size();
        for(int i=0; i<len/2; ++i){
            char t = str[i];
            str[i] = str[len-1-i];
            str[len-1-i] = t;
        }
        return str;
    }
};

双下标

class Solution {
public:
    string solve(string str) {
        int i=0, j=str.size()-1;
        while(i<j){
            char t = str[i];
            str[i] = str[j];
            str[j] = t;
            ++i;--j;
        }
        return str;
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务