https://leetcode.com/problems/count-the-number-of-special-characters-i
Count the Number of Special Characters I - LeetCode
Can you solve this real interview question? Count the Number of Special Characters I - You are given a string word. A letter is called special if it appears both in lowercase and uppercase in word. Return the number of special letters in word. Example 1
leetcode.com
vector 자료구조를 사용해본 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
📑 word가 가지고 있는 소문자, 대문자에 대한 vector lower, upper를 각각 선언해 false로 초기화합니다
📑 정답 변수 ans를 선언 후 0으로 초기화합니다.
📔 풀이과정
📑 word의 문자 순회
bytes()로 순회하면 - 연산으로 usize의 index 접근이 가능합니다. 이를 순회하며 소문자라면 lower에 대문자라면 upper를 true로 저장합니다.
📑 알파뱃 순회 lower와 upper가 둘다 있다면 ans값을 1씩 추가합니다.
📑 시간 복잡도
O(n): word의 크기만큼 배열 순회하는 것이 최대 복잡도이기 때문입니다.
📑 공간 복잡도
O(1): 알파뱃 개수*2 만큼의 배열 공간만 선언하면 되기 때문입니다
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 Rust
impl Solution {
pub fn number_of_special_chars(word: String) -> i32 {
let mut lower = vec![false; 26];
let mut upper = vec![false; 26];
let mut ans = 0;
for word_byte in word.bytes() {
if word_byte.is_ascii_lowercase() {
lower[(word_byte - b'a') as usize] = true;
} else if word_byte.is_ascii_uppercase() {
upper[(word_byte - b'A') as usize] = true;
}
}
for i in 0..26 {
if lower[i] && upper[i] {
ans += 1;
}
}
ans
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.