Coding Test/LeetCode

[LeetCode] 344. Reverse String c++

owls 2022. 12. 26. 16:49
728x90
  • 문제

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.

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

 

input으로 주어지는 벡터 s의 요소들의 순서를 반대로 뒤집는 문제입니다.

 

  • 문제 해결
class Solution {
public:
    void reverseString(vector<char>& s) {
        
        reverse(s.begin(), s.end());
        
    }
};

 

다른 풀이

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

 

다른 풀이2

stack을 사용한 문제 풀이입니다.

class Solution {
public:
    void reverseString(vector<char>& s) {
        
        stack<char> st;
        for(const auto& it: s){
            st.push(it);
        }
        s.clear();
        while(!st.empty()){
            char ch = st.top();
            st.pop();
            s.emplace_back(ch);
                        
        }
    }
};

728x90