forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0038_count_and_say.rs
78 lines (73 loc) · 1.74 KB
/
n0038_count_and_say.rs
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* [38] Count and Say
*
* The count-and-say sequence is the sequence of integers with the first five terms as following:
*
*
* 1. 1
* 2. 11
* 3. 21
* 4. 1211
* 5. 111221
*
*
* 1 is read off as "one 1" or 11.<br />
* 11 is read off as "two 1s" or 21.<br />
* 21 is read off as "one 2, then one 1" or 1211.
*
* Given an integer n where 1 <= n <= 30, generate the n^th term of the count-and-say sequence.
*
* Note: Each term of the sequence of integers will be represented as a string.
*
*
*
* Example 1:
*
*
* Input: 1
* Output: "1"
*
*
* Example 2:
*
*
* Input: 4
* Output: "1211"
*
*/
pub struct Solution {}
// submission codes start here
use std::char::from_digit;
impl Solution {
pub fn count_and_say(n: i32) -> String {
let mut res = vec!['1'];
for _ in 0..n-1 {
let mut temp = Vec::new();
let mut i = 0_usize;
while i < res.len() {
let mut j = i + 1;
while j < res.len() && res[j] == res[i] {
j += 1;
}
temp.push(from_digit((j - i) as u32, 10).unwrap());
temp.push(res[i]);
i = j;
}
res = temp;
}
res.iter().collect()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_38() {
assert_eq!(Solution::count_and_say(1), "1");
assert_eq!(Solution::count_and_say(2), "11");
assert_eq!(Solution::count_and_say(3), "21");
assert_eq!(Solution::count_and_say(4), "1211");
assert_eq!(Solution::count_and_say(5), "111221");
}
}