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--;
}
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 190] Reverse Bits (0) | 2020.12.03 |
---|---|
[leetcode 242] Valid Anagram (0) | 2020.12.01 |
[leetcode 350] Intersection of Two Arrays II (0) | 2020.12.01 |
[leetcode 191] Number of 1 Bits (0) | 2020.11.30 |
[leetcode 237] Delete Node in a Linked List (0) | 2020.11.27 |
댓글