Solve valid-anagram.
This commit is contained in:
		
							parent
							
								
									f794fd532c
								
							
						
					
					
						commit
						84ceb51cb1
					
				| 
						 | 
					@ -7,4 +7,5 @@ pub mod plus_one;
 | 
				
			||||||
pub mod reverse_integer;
 | 
					pub mod reverse_integer;
 | 
				
			||||||
pub mod roman_to_integer;
 | 
					pub mod roman_to_integer;
 | 
				
			||||||
pub mod two_sum;
 | 
					pub mod two_sum;
 | 
				
			||||||
 | 
					pub mod valid_anagram;
 | 
				
			||||||
pub mod valid_parenthesis;
 | 
					pub mod valid_parenthesis;
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
| 
						 | 
					@ -0,0 +1,31 @@
 | 
				
			||||||
 | 
					pub fn is_anagram(a: String, b: String) -> bool {
 | 
				
			||||||
 | 
					  // Both strings must have the same length otherwise they can't be anagrams.
 | 
				
			||||||
 | 
					  if a.len() != b.len() {
 | 
				
			||||||
 | 
					    return false;
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  // Sort both strings' characters so they're in alphabetical order.
 | 
				
			||||||
 | 
					  let mut a = a.chars().collect::<Vec<_>>();
 | 
				
			||||||
 | 
					  a.sort();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  let mut b = b.chars().collect::<Vec<_>>();
 | 
				
			||||||
 | 
					  b.sort();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  // And if they are equal, then they're anagrams.
 | 
				
			||||||
 | 
					  a == b
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					#[test]
 | 
				
			||||||
 | 
					fn test_valid_anagram() {
 | 
				
			||||||
 | 
					  let samples = [
 | 
				
			||||||
 | 
					    (("💖🌠banana", "an💖anab🌠"), true),
 | 
				
			||||||
 | 
					    (("anagram", "nagaram"), true),
 | 
				
			||||||
 | 
					    (("bats", "tabs"), true),
 | 
				
			||||||
 | 
					    (("rat", "cat"), false),
 | 
				
			||||||
 | 
					    (("bats", "bat"), false),
 | 
				
			||||||
 | 
					  ];
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  for ((a, b), expected) in samples {
 | 
				
			||||||
 | 
					    assert_eq!(is_anagram(a.to_string(), b.to_string()), expected);
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
		Loading…
	
		Reference in New Issue