@@ -2,54 +2,34 @@ use crate::q::Solution;
2
2
3
3
#[ allow( unused) ]
4
4
impl Solution {
5
- // 给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。
6
- // 0 <= A.length <= 20000
7
- // 0 <= B.length <= 20000
8
- // A 和 B 仅由小写字母构成。
9
- pub fn buddy_strings ( a : String , b : String ) -> bool {
10
- if a. len ( ) != b. len ( ) {
11
- return false ;
5
+ pub fn buddy_strings ( s : String , goal : String ) -> bool {
6
+ // 方法1
7
+ // 交换一次的情况下要相等
8
+ // 1. 那么首先要保证的就是两个字符串的长度要相等
9
+ // 2. 然后两个字符串的字符频率要一样
10
+ // 3. 接着检查两个字符串的对位不相同的字符数量是否为2或者没有
11
+ // 3.1 如果为2,那一定可以交换
12
+ // 3.2 如果没有,那么就要判断是否至少有一个字符的频率要大于等于2(至少2个才可以交换)
13
+ // AC 0ms 2.2mb 34/34
14
+ let s: Vec < char > = s. chars ( ) . collect ( ) ;
15
+ let goal: Vec < char > = goal. chars ( ) . collect ( ) ;
16
+ if s. len ( ) != goal. len ( ) { return false ; }
17
+ let mut diff = 0 ;
18
+ let mut freq_s = vec ! [ 0 ; 26 ] ;
19
+ let mut freq_goal = vec ! [ 0 ; 26 ] ;
20
+ for i in 0 ..s. len ( ) {
21
+ if s[ i] != goal[ i] { diff += 1 ; }
22
+ freq_s[ ( s[ i] as u8 - b'a' ) as usize ] += 1 ;
23
+ freq_goal[ ( goal[ i] as u8 - b'a' ) as usize ] += 1 ;
12
24
}
13
- let mut buckets = vec ! [ 0 ; 256 ] ;
14
- let a = a. chars ( ) . collect :: < Vec < char > > ( ) ;
15
- let b = b. chars ( ) . collect :: < Vec < char > > ( ) ;
16
- let mut swap = ( 0 , 0 ) ;
17
- let mut count = 0 ;
18
- for i in 0 ..a. len ( ) {
19
- let ch1 = a[ i] as u8 ;
20
- let ch2 = b[ i] as u8 ;
21
- buckets[ ch1 as usize ] += 1 ;
22
-
23
- if ch1 != ch2 {
24
- if count > 2 {
25
- return false ;
26
- }
27
- if count == 0 {
28
- swap. 0 = ch1;
29
- swap. 1 = ch2;
30
- } else if swap. 0 != ch2 || swap. 1 != ch1 {
31
- return false ;
32
- }
33
- count += 1 ;
34
- }
25
+ for i in 0 ..26 {
26
+ if freq_s[ i] != freq_goal[ i] { return false ; }
35
27
}
36
- if count == 0 {
37
- for i in 0 ..256 {
38
- if buckets[ i] > 1 {
39
- return true ;
40
- }
28
+ if diff == 0 {
29
+ for i in 0 ..26 {
30
+ if freq_s[ i] > 1 { return true ; }
41
31
}
42
32
}
43
- count != 0
33
+ diff == 2
44
34
}
45
- }
46
-
47
- #[ test]
48
- fn test_q859 ( ) {
49
- assert_eq ! ( true , Solution :: buddy_strings( "ba" . to_string( ) , "ab" . to_string( ) ) ) ;
50
- assert_eq ! ( false , Solution :: buddy_strings( "ab" . to_string( ) , "ab" . to_string( ) ) ) ;
51
- assert_eq ! ( false , Solution :: buddy_strings( "abc" . to_string( ) , "abc" . to_string( ) ) ) ;
52
- assert_eq ! ( false , Solution :: buddy_strings( "abcd" . to_string( ) , "abcd" . to_string( ) ) ) ;
53
- assert_eq ! ( true , Solution :: buddy_strings( "aba" . to_string( ) , "aba" . to_string( ) ) ) ;
54
- assert_eq ! ( true , Solution :: buddy_strings( "aa" . to_string( ) , "aa" . to_string( ) ) ) ;
55
35
}
0 commit comments