[Programmers] #120850 - 문자열 정렬하기 (1) [Java][C++][Python]
소문자와 숫자로 이루어진 문자열에서 숫자만 골라 오름차순으로 정렬한 리스트를 구하는 문제.
[Programmers] #120850 - 문자열 정렬하기 (1) [Java][C++][Python]
1. 아이디어
문자열을 순회하며 숫자에 해당하는 글자만 골라 정수로 변환해 모은 뒤, 오름차순으로 정렬해 반환한다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N \log N)$ | $O(N)$ |
($N$ = my_string의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
class Solution {
public int[] solution(String my_string) {
List<Integer> list = new ArrayList<>();
for (char c : my_string.toCharArray()) {
if (Character.isDigit(c)) list.add(c - '0');
}
return list.stream().sorted().mapToInt(Integer::intValue).toArray();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(string my_string) {
vector<int> v;
for (char c : my_string) {
if (isdigit(c)) v.push_back(c - '0');
}
sort(v.begin(), v.end());
return v;
}
1
2
def solution(my_string):
return sorted(int(c) for c in my_string if c.isdigit())
This post is licensed under CC BY 4.0 by the author.