1pub struct Solution;
35
36impl Solution {
37 pub fn is_subsequence(s: String, t: String) -> bool {
38 Self::simple_match(&s, &t)
41 }
42
43 pub fn simple_match(s: &str, t: &str) -> bool {
45 t.chars().try_fold(s.chars().peekable(), |mut s, t| match s.peek() {
46 Some(&c) if c == t => { s.next(); Some(s) }
47 Some(_) => Some(s),
48 None => None, }).map_or(true, |mut s| s.next().is_none())
50 }
51}
52
53pub struct Matching {
56 pos: Vec<[Option<usize>; 26]>,
57}
58
59impl Matching {
60
61 pub fn new(target: String) -> Self {
62 let len = target.len();
63 let t: Vec<_> = target.chars().collect();
64 let mut pos: Vec<[Option<usize>; 26]> = Vec::with_capacity(len);
65 while pos.len() < len {
66 pos.push([None; 26]);
67 }
68
69 for i in (0..len).rev() {
70 for j in 0..26usize {
71 if t[i] as usize == j + 'a' as usize {
72 pos[i][j] = Some(i);
73 } else {
74 pos[i][j] = if i + 1 < len {
75 pos[i + 1][j]
76 } else {
77 None
78 };
79 }
80 }
81 }
82
83 Self {
84 pos,
85 }
86 }
87
88 pub fn is_match(&self, s: String) -> bool {
89 if s.len() > self.pos.len() {
90 return false;
91 }
92 let mut x = 0;
93 for c in s.chars() {
94 let char_offset = c as usize - 'a' as usize;
95 if let Some(v) = self.pos.get(x).and_then(|v| v[char_offset]) {
96 x = v + 1;
97 } else {
98 return false;
99 }
100 }
101 true
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[test]
110 fn test() {
111 let t1 = |s: &str, t: &str| Solution::is_subsequence(s.into(), t.into());
112 let t2 = |s: &str, t: &str| Matching::new(t.into()).is_match(s.into());
113
114 let s = "";
115 let t = "abc";
116 assert!(t1(s, t));
117 assert!(t2(s, t));
118
119 let s = "abc";
120 let t = "ahbgdc";
121 assert!(t1(s, t));
122 assert!(t2(s, t));
123
124 let s = "axc";
125 let t = "ahbgdc";
126 assert!(!t1(s, t));
127 assert!(!t2(s, t));
128
129 let s = "axc";
130 let t = "";
131 assert!(!t1(s, t));
132 assert!(!t2(s, t));
133
134 let s = "aaaaaa";
135 let t = "bbaaaa";
136 assert!(!t1(s, t));
137 assert!(!t2(s, t));
138
139 let s = "twn";
140 let t = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxtxxxxxxxxxxxxxxxxxxxxwxxxxxxxxxxxxxxxxxxxxxxxxxn";
141 assert!(t1(s, t));
142 assert!(t2(s, t));
143 }
144}