https://leetcode.com/problems/long-pressed-name/description/
Long Pressed Name - LeetCode
Can you solve this real interview question? Long Pressed Name - Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed cha
leetcode.com
문자열을 다뤄보는 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
* rust의 경우 String에 대한 index 접근이 불가하므로 Vec<char>로 형변환해 따로 변수에 저장해줍니다.
📔 풀이과정
two pointer를 사용합니다.
name의 index i와 typed의 index j를 선언 후 0으로 초기화해줍니다.
1. typed.size만큼 while loop를 수행합니다.
2. name[i], typed[j]가 같다면 비교가 완료되었으므로 i, j를 각각 1씩 증가시켜 줍니다.
3. name[i]과 typed[j]가 다르다면 typed의 long pressed가능성을 고려해 인접 원소가 다른 만큼 j를 증가시켜줍니다.
4. 이외의 경우 틀리게 입력한 경우이므로 false를 반환합니다.
📔 정답 출력 | 반환
* 비교한 최종결과가 name.size()인지 i와 비교해 같으면 true를 아니면 false를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int i = 0, j = 0;
while(j < typed.size()) {
if(i < name.size() && name[i] == typed[j]) i++,j++;
else if(j > 0 && typed[j] == typed[j-1]) j++;
else return false;
}
return i == name.size();
}
};
📔 Rust
impl Solution {
pub fn sort_array_by_parity_ii(nums: Vec<i32>) -> Vec<i32> {
let mut ans: Vec<i32> = Vec::new();
let mut odd = Vec::new();
let mut even = Vec::new();
for n in nums {
if n % 2 == 1 {
odd.push(n);
} else {
even.push(n);
}
}
while !odd.is_empty() || !even.is_empty() {
if let Some(e) = even.pop() {
ans.push(e);
}
if let Some(o) = odd.pop() {
ans.push(o);
}
}
ans
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++, Rust) - LeetCode (easy) 941. Valid Mountain Array (0) | 2023.09.11 |
---|---|
(C++) - LeetCode (easy) 941. Valid Mountain Array (0) | 2023.09.08 |
(C++, Rust) - LeetCode (easy) 922. Sort Array By Parity II (0) | 2023.09.01 |
(C++, Rust) - LeetCode (easy) 908. Smallest Range I (0) | 2023.08.28 |
(C++, Rust) - LeetCode (easy) 896. Monotonic Array (0) | 2023.08.22 |