File tree 1 file changed +36
-0
lines changed
scripts/algorithms/F/Find and Replace Pattern
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 0 ms (Top 100.0%) | Memory: 2.20 MB (Top 37.5%)
2
+
3
+ use std:: collections:: HashMap ;
4
+ impl Solution {
5
+ pub fn find_and_replace_pattern ( words : Vec < String > , pattern : String ) -> Vec < String > {
6
+ let mut ret = vec ! [ ] ;
7
+
8
+ for word in words {
9
+ if Self :: check ( & word. chars ( ) . collect :: < Vec < char > > ( ) [ 0 ..] , & pattern. chars ( ) . collect :: < Vec < char > > ( ) [ 0 ..] ) {
10
+ ret. push ( word. clone ( ) ) ;
11
+ }
12
+ }
13
+
14
+ ret
15
+ }
16
+
17
+ fn check ( s : & [ char ] , t : & [ char ] ) -> bool {
18
+ let mut mp1: HashMap < char , char > = HashMap :: new ( ) ;
19
+ let mut mp2: HashMap < char , char > = HashMap :: new ( ) ;
20
+ for i in 0 ..s. len ( ) {
21
+ let flag1 = if mp1. contains_key ( & s[ i] ) { 1 } else { 0 } ;
22
+ let flag2 = if mp2. contains_key ( & t[ i] ) { 1 } else { 0 } ;
23
+ if flag1 + flag2 == 1 { return false }
24
+ if flag1 + flag2 == 2 {
25
+ let ( mut c1, mut c2) = ( ' ' , ' ' ) ;
26
+ if let Some ( c) = mp1. get ( & s[ i] ) { c1 = * c; }
27
+ if let Some ( c) = mp2. get ( & t[ i] ) { c2 = * c; }
28
+ if c1 != t[ i] || c2 != s[ i] { return false }
29
+ continue ;
30
+ }
31
+ mp1. insert ( s[ i] , t[ i] ) ;
32
+ mp2. insert ( t[ i] , s[ i] ) ;
33
+ }
34
+ true
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments