LeetCode - ReverseString

题目原址:https://leetcode.com/problems/reverse-string/?tab=Description

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

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

解题思路:这是一道关于字符串和反序的问题,现在提供两种解决方法。

法1. 新建一个字符串S2,反序取出原字符串S1中的字符放入S2中。这样的好处是我们保留了原字符串,但是会占用两倍的内存。在Leetcode中会报错为内存不够。

法2. 将原字符串的首尾对调。

下面分别给出两种解的代码片段:

//Solution1:
class Solution {
public:
    string reverseString(string s) 
    {
        int slength = s.size();
        string newstring;
        for(int i = 0; i < slength; i++)
        {
            newstring = newstring+s[slength - i-1];
        }
        return newstring;
    }
};
//Solution2:
class Solution {
public:
    string reverseString(string s) 
    {
        int slength = s.size();
        char temp;
        for (int i = 0; i < slength/2; i++)
        {
            temp = s[i];
            s[i] = s[slength - i - 1];
            s[slength - i - 1] = temp;  
        }
        return s;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值