티스토리 뷰
728x90
반응형
Problem
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
문자 배열이 주어질 때 해당 문자 배열을 뒤집는 기능을 구현하는 문제입니다.
상수 메모리를 추가로 사용할 수 있습니다.
변수 temp 하나만 사용해서 배열의 양 끝에서부터 swap 해주면 간단히 해결할 수 있습니다.
public class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left++] = s[right];
s[right--] = temp;
}
}
}
Test
package io.lcalmsky.leetcode.reverse_string;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void testAll() {
assertAll(
() -> test(new char[]{'h', 'e', 'l', 'l', 'o'}, new char[]{'o', 'l', 'l', 'e', 'h'}),
() -> test(new char[]{'H', 'a', 'n', 'n', 'a', 'h'},
new char[]{'h', 'a', 'n', 'n', 'a', 'H'})
);
}
private void test(char[] given, char[] expected) {
// when
Solution solution = new Solution();
solution.reverseString(given);
// then
assertArrayEquals(expected, given);
}
}
728x90
반응형
'Algorithm > LeetCode Daily Challenge' 카테고리의 다른 글
856. Score of Parentheses (0) | 2022.04.24 |
---|---|
31. Next Permutation (0) | 2022.04.23 |
344. Reverse String (0) | 2022.04.22 |
1046. Last Stone Weight (0) | 2022.04.19 |
923. 3Sum With Multiplicity (0) | 2022.04.18 |
11. Container With Most Water (0) | 2022.04.16 |
댓글
공지사항
- Total
- 83,835
- Today
- 55
- Yesterday
- 439
링크
TAG
- @ManyToOne
- Spring Boot Tutorial
- leetcode
- leetcode bst
- spring boot application
- Spring Data JPA
- 스프링 부트 튜토리얼
- spring boot app
- Spring Boot JPA
- 스프링 부트
- 스프링 부트 jwt
- leetcode stack
- JPA
- 알고리즘
- spring boot jwt
- QueryDSL
- Jackson
- 스프링 데이터 jpa
- intellij
- Java
- r
- gRPC
- 스프링 부트 애플리케이션
- 스프링부트
- 스프링 부트 회원 가입
- proto3
- JSON
- leetcode binary search
- Linux
- Spring Boot