
Description
주어진 문자배열의 내용을 반전(reverse)시키는 문제입니다.
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:
- 1 <= s.length <= 10^5
- s[i] is a printable ascii character.
Solution 1. Two Pointers - Reverse()
public void reverseString(char[] s) {
int start = 0;
int end = s.length-1;
while(start < end){
char temp = s[start];
s[start++] = s[end];
s[end--] = temp;
}
}
두개의 포인트를 양끝에 두고 문자열 swap후 한 칸씩 움직이는 것을 반복하여 전체 문자열을 반전시킵니다.
- 시간복잡도 : O(N)
- 공간복잡도 : O(N)
Reference
Reverse String - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 350. Intersection of Two Arrays II - 문제풀이 (0) | 2022.01.20 |
---|---|
[LeetCode] 557. Reverse Words in a String III - 문제풀이 (0) | 2022.01.20 |
[LeetCode] 167. Two Sum II - Input Array Is Sorted - 문제풀이 (0) | 2022.01.20 |
[LeetCode] 283. Move Zeroes - 문제 풀이 (0) | 2022.01.20 |
[LeetCode] 142. Linked List Cycle II - 문제 풀이 (0) | 2022.01.20 |