leetcode-344-Reverse-String

描述


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

Example:

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

分析


一左一右,向中间推进,左右交换。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string reverseString(string s) {
int len = s.size();
int left = 0;
int right = len - 1;
string res = s;

while(left < right) {
swap(res[left], res[right]);
left++;
right--;
}
return res;
}
};

相关问题


(E) Reverse Vowels of a String

题目来源