zoukankan      html  css  js  c++  java
  • 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/

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

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

    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中间变量,最熟悉的方法。

      tmp=i;

      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;

  • 相关阅读:
    notebook笔记
    from __future__ import absolute_import
    GUI
    version_info
    函数参数
    None
    exec、eval
    os
    IGeometry接口
    IGeometry接口
  • 原文地址:https://www.cnblogs.com/wdfwolf3/p/5484675.html
Copyright © 2011-2022 走看看