Welcome to Subscribe On Youtube

Question

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

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

 

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

 

Constraints:

Algorithm

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

Code

  • 
    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();
            }
        }
    }
    
    ############
    
    class Solution {
        public void reverseString(char[] s) {
            for (int i = 0, j = s.length - 1; i < j; ++i, --j) {
                char t = s[i];
                s[i] = s[j];
                s[j] = t;
            }
        }
    }
    
  • // 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:
        def reverseString(self, s: List[str]) -> None:
            """
            Do not return anything, modify s in-place instead.
            """
            s[:] = s[::-1]
    
    ############
    
    class Solution(object):
      def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]
    
    
  • func reverseString(s []byte) {
    	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
    		s[i], s[j] = s[j], s[i]
    	}
    }
    
  • /**
     * @param {character[]} s
     * @return {void} Do not return anything, modify s in-place instead.
     */
    var reverseString = function (s) {
        for (let i = 0, j = s.length - 1; i < j; ++i, --j) {
            [s[i], s[j]] = [s[j], s[i]];
        }
    };
    
    
  • impl Solution {
        pub fn reverse_string(s: &mut Vec<char>) {
            let n = s.len();
            let mut l = 0;
            let mut r = n - 1;
            while l < r {
                s.swap(l, r);
                l += 1;
                r -= 1;
            }
        }
    }
    
    

All Problems

All Solutions