[LeetCode] 344. Reverse String

Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Thought process:
Use two pointers: one from the start of the string, the other from the end of the string. Swap the characters pointed until they collide.
Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    string reverseString(string s) {
        int i = 0;
        int j = s.length() - 1;
        
        while (i < j) {
            swap(s[i], s[j]);
            i++;
            j--;
        }
        
        return s;
    }
};

Time complexity:

O(n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula