[Programmers] #181890 - 왼쪽 오른쪽 [Java][C++][Python]
[Programmers] #181890 - 왼쪽 오른쪽 [Java][C++][Python]
1. 아이디어
"l"과 "r" 중 먼저 나오는 쪽만 보므로 앞에서부터 훑다가 처음 만나는 "l" 또는 "r"에서 바로 정한다. "l"이면 그 앞쪽을, "r"이면 그 뒤쪽을 반환한다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;
class Solution {
public String[] solution(String[] str_list) {
int n = str_list.length;
for (int i = 0; i < n; i++) {
if (str_list[i].equals("l")) return Arrays.copyOfRange(str_list, 0, i);
if (str_list[i].equals("r")) return Arrays.copyOfRange(str_list, i + 1, n);
}
return new String[0];
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
vector<string> solution(vector<string> str_list) {
for (int i = 0; i < str_list.size(); i++) {
if (str_list[i] == "l") return vector<string>(str_list.begin(), str_list.begin() + i);
if (str_list[i] == "r") return vector<string>(str_list.begin() + i + 1, str_list.end());
}
return {};
}
1
2
3
4
5
6
7
8
def solution(str_list):
for i, s in enumerate(str_list):
if s == "l":
return str_list[:i]
if s == "r":
return str_list[i + 1 :]
return []
This post is licensed under CC BY 4.0 by the author.