[LeetCode-344]Reverse String(c++)

来源:互联网 发布:淘宝怎么看发货地址 编辑:程序博客网 时间:2024/05/29 19:48

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

Example:
Given s = "hello", return "olleh".

分析:即将一个给定的字符串,反向输出。

采用for循环,在数组中同时由前向后、由后向前进行字符两两交换;

若字符串有奇数个字符,中间的字符不动;

若字符有偶数个字符,正好可以完成两两交换。

class Solution {public:    string reverseString(string s) {        char temp;        int len=s.length();        for(int i=0;i<len/2;i++){            temp=s[i];            s[i]=s[len-1-i];            s[len-1-i]=temp;        }        return s;    }};


0 0