반응형
https://leetcode.com/problems/di-string-match/description/
DI String Match - LeetCode
Can you solve this real interview question? DI String Match - A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: * s[i] == 'I' if perm[i] < perm[i + 1], and * s[i] == 'D' if perm
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
s의 길이 sz, 숫자 l, r과 정답 변수 ans를 선언해 줍니다.
📔 풀이과정
1. s의 원소를 순회하며 'I'인경우 수가 증가하고 'D'인 경우 감소하도록 수를 구성하면 됩니다. l을 0부터 시작해 I가 나올때마다 ans에 l을 push_back 후 1증가시켜줍니다. D가 나왔다면 ans에 r을 push_back한 후 r을 1감소시켜줍니다.2. 마지막 원소 l을 넣어줍니다. s의 마지막에 어떤 문자가 오든 상관없이 l값은 마지막 값을 저장하고 있기 때문입니다.*rust의 경우 for loop로 짜는것이 함수형보다 깔끔합니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
vector<int> diStringMatch(string s) {
int sz = s.size();
int l = 0;
int r = sz;
vector <int> ans;
for(int i = 0; i < sz; i++) {
if(s[i] == 'I') {
ans.push_back(l++);
}
if(s[i] == 'D') {
ans.push_back(r--);
}
}
ans.push_back(l);
return ans;
}
};
📔 Rust
impl Solution {
pub fn di_string_match(s: String) -> Vec<i32> {
let sz = s.len();
let mut l = 0;
let mut r = sz as i32;
let mut ans:Vec<i32> = Vec::new();
println!("{:?}",s.chars());
for c in s.chars() {
if c == 'I' {
ans.push(l);
l += 1;
} else {
ans.push(r);
r -= 1;
}
}
ans.push(l);
return ans;
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 999. Available Captures for Rook (0) | 2023.09.22 |
---|---|
(Python3) - LeetCode (easy) 989. Add to Array-Form of Integer (0) | 2023.09.18 |
(C++) - LeetCode (easy) 941. Valid Mountain Array (0) | 2023.09.08 |
(C++, Rust) - LeetCode (easy) 925. Long Pressed Name (0) | 2023.09.04 |
(C++, Rust) - LeetCode (easy) 922. Sort Array By Parity II (0) | 2023.09.01 |