344. Reverse String

題目原文

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

Example 1:

Input: "hello"
Output: "olleh"

Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

解題思路

  1. 第一個字元與最後一個字元交換。

  2. 第二個字元與倒數第二個字元交換。

  3. 以此類推。

程式解答

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

Last updated

Was this helpful?