Reverse String

2024. 10. 6. 11:03알고리즘/Leetcode

반응형

Solution

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.

 

 

Examples

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"]

 

 

Explanation

class Solution {
    public void reverseString(char[] s) {
        int start = 0, end = s.length - 1;

        while(start < end){
            char tmp = s[start];
            s[start] = s[end];
            s[end] = tmp;

            start++; end--;
        }

    }
}

 

Using a two pointer algorithm, we solve this problem. 

Firstly, two variables are created to point the first and the last indexes.

Two values swap each other using a while loop and then increment start variable and decrement end variable. 

반응형

'알고리즘 > Leetcode' 카테고리의 다른 글

First Unique Character in a String  (2) 2024.10.08
Reverse Integer  (0) 2024.10.07
Valid Sudoku  (2) 2024.10.04
Two Sum  (1) 2024.09.24
Move Zeroes  (2) 2024.09.23