题目原址: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;
}
};