Question

Formatted question description: https://leetcode.ca/all/344.html

 344	Reverse String

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

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

 @tag-string
 @tag-2pointers

Algorithm

Go from both ends to the middle while swapping characters on both sides.

Code

Java

  • 
    public class Reverse_String {
    
        class Solution {
            public void reverseString(char[] s) {
    
                int l = 0;
                int r = s.length - 1;
    
                while (l < r) {
                    char tmp = s[l];
                    s[l] = s[r];
                    s[r] = tmp;
                    l++;
                    r--;
                }
            }
        }
    
        class Solution_cheat {
            public String reverseString(String input) {
    
                StringBuilder s = new StringBuilder(input);
                s.reverse();
    
                return s.toString();
            }
        }
    }
    
  • // OJ: https://leetcode.com/problems/reverse-string/
    // Time: O(N)
    // Space: O(1)
    class Solution {
    public:
        void reverseString(vector<char>& s) {
            int i = 0, j = s.size() - 1;
            while (i < j) swap(s[i++], s[j--]);
        }
    };
    
  • class Solution(object):
      def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]
    
    

All Problems

All Solutions