题目:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
翻译:
写一个函数将一个字符串作为输入并且返回字符串的倒序。
例子:
给定 s = "hello", 返回olleh".
思路:
设置两个指针 p , q ,让他们分别指向字符串的头和尾,只要 p<=q ,就不断地交换 p 和 q 指向的字符,直到 p>q 。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string reverseString(string s) {
int p, q;
p = 0;
q = s.size() - 1;
while (p <= q) {
int temp;
temp = s[p];
s[p] = s[q];
s[q] = temp;
p++;
q--;
}
return s;
}
};
int main()
{
Solution s;
string str="hello";
string result;
result = s.reverseString(str);
cout << result;
return 0;
}