티스토리 뷰

https://leetcode.com/problems/count-and-say/

 

Count and Say - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

숫자를 입력받으면 숫자에 대한 counting을 진행한다

n = 1 return 1

n = 2 return 11 (1이 1개)

n = 3 return 21 (1이 2개)

n = 4 return 1211 (2가 1개, 1이 1개)

n = 5 return 111221 (1이 1개, 2가 1개, 1이2개)

 

impl Solution {
    pub fn count_and_say(n: i32) -> String {
        let base = "1";
        Self::produce_next(1, n, base.to_string())
    }

    fn produce_next(current: i32, end: i32, str: String) -> String {
        if current == end {
            return str;
        }
        let mut prev : char = ' ';
        let mut freq : i32 = 0;
        let mut result = String::from("");
        for ch in str.chars() {
            if prev == ' ' {
                prev = ch;
                freq += 1;
            } else if ch == prev {
                freq += 1;
            } else {
                result.push_str(&format!("{}{}", freq, prev));
                prev = ch;
                freq = 1;
            };
        }

        result.push_str(&format!("{}{}", freq, prev));
        Self::produce_next(current + 1, end, result)
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함