본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 344] Reverse String

by m2162003 2020. 12. 1.

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

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

 

Example 1:

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

Example 2:

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

 

문제 난이도: easy

추가 메모리를 사용하지 말라고 했으니 배열의 중간지점까지 가면서 양끝 배열값을 swap해준다.

class Solution {
public:
    void reverseString(vector<char>& s) {
        
        int len = s.size();
        
        int i=0, j = len-1;
        while(i<j){
            swap(s[i], s[j]);
            i++;
            j--;
        }
    }
};

댓글