forked from YuriSpiridonov/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
859.BuddyStrings.py
70 lines (61 loc) · 2.05 KB
/
859.BuddyStrings.py
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
"""
Given two strings A and B of lowercase letters, return true if you can
swap two letters in A so the result is equal to B, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed)
such that i != j and swapping the characters at A[i] and A[j]. For example,
swapping at indices 0 and 2 in "abcd" results in "cbad".
Example:
Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is
equal to B.
Example:
Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b',
which results in "ba" != B.
Example:
Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is
equal to B.
Example:
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example:
Input: A = "", B = "aa"
Output: false
Constraints:
- 0 <= A.length <= 20000
- 0 <= B.length <= 20000
- A and B consist of lowercase letters.
"""
#Difficulty: Easy
#29 / 29 test cases passed.
#Runtime: 196 ms
#Memory Usage: 14.4 MB
#Runtime: 196 ms, faster than 7.87% of Python3 online submissions for Buddy Strings.
#Memory Usage: 14.4 MB, less than 25.71% of Python3 online submissions for Buddy Strings.
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if not A or not B or len(A) != len(B):
return False
i = len(A) - 1
index = None
while i >= 0:
if A[i] != B[i]:
if not index:
index = i
else:
B = list(B)
B[i], B[index] = B[index], B[i]
B = ''.join(B)
return A == B
i -= 1
if A == B:
count = 0
for char in A:
count = max(count, A.count(char))
return count > 1
else:
False