The Solution to Leetcode 344 Reverse String

来源:互联网 发布:浙大知乎 沈璐 编辑:程序博客网 时间:2024/05/29 15:39

Question:

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

Example:
Given s = "hello", return "olleh".

思路:将字符串首末字符调换,第二个字符与倒数第二个字符调换,以此类推。

Answer:

class Solution {public:    string reverseString(string s) {        int i=0;        int j=s.size()-1;        char temp;        while(i<j)        {         temp=s[i];         s[i++]=s[j];         s[j--]=temp;        }         return s;    }};

run code results:

Your input
"hello"
Your answer
"olleh"
Expected answer
"olleh"

0 0