leetcode344——Reverse String(C++)

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

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

我的博客:http://www.cnblogs.com/wdfwolf3/spa

这道题就是简单的字符串逆置,在C++中字符串类型能够做为数组方式处理,因此经典的数组逆置就能够完成。这里提供两种思路:code

1.classic方法头尾交换(16ms)blog

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

2.recursion方法分治递归(44ms)递归

将字符串分为先后两部分,分别逆置而后合并起来,合并时天然是后半部分在前,前半部分在后。用到字符串截取函数string.substr(),它接收两个参数,第一个为位置索引,即截取的开始位置,默认参数为0,就是字符串的开始;第二个参数为截取字符的数目,若是省略,就是指截取到字符串的末尾。索引

class Solution {
public:
    string reverseString(string s) {
        int length=s.size();
        if(length<2)
            return s;
        return reverseString(s.substr(length/2))+reverseString(s.substr(0,length/2));
    }
    
};

 

P.S.最后关于swap交换元素介绍两个思路:字符串

1.tmp中间变量,最熟悉的方法。get

  tmp=i;input

  i=tmp;

  j=tmp;

2.bit的按位抑或^原理,即m^m=0,0^m=m。

  m=m&n;

  n=m&n;                 等价于      n=m&n&n=m;

  m=m&n;              m=m&n&m=n;