This repository was archived by the owner on May 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path859. Buddy Strings.cpp
More file actions
76 lines (62 loc) · 1.76 KB
/
859. Buddy Strings.cpp
File metadata and controls
76 lines (62 loc) · 1.76 KB
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
71
72
73
74
75
76
class Solution {
public:
bool buddyStrings(string A, string B) {
int m = A.length();
int n = B.length();
if(m==0 || n==0 || m!=n)
return false;
int mismatch_count=0;
char a1,b1,a2,b2;
unordered_map<char,int> mp;
for(int i=0;i<m;i++)
{
if(A[i]!=B[i])
{
if(mismatch_count==0)
{
a1=A[i];
b1= B[i];
mismatch_count++;
}
else if(mismatch_count==1)
{
a2=A[i];
b2=B[i];
mismatch_count++;
}
else if(mismatch_count==2)
{
return false;
}
}
mp[A[i]]++;
if(mismatch_count>2)
return false;
}
if(mismatch_count==2)
{
if(a2==b1 && a1==b2)
return true;
return false;
}
else if(mismatch_count==0)
{
if(A.compare(B)==0) //Eg:ababa shoudl return true but abcd false..so checking such things
{
for(auto i = mp.begin();i!=mp.end();i++)
{
if(i->second>=2)
return true;
}
return false;
}
for(int i=1;i<m;i++) //Eg: aaaaa true
{
if(A[0]!=B[i])
return false;
}
return true;
}
return false;
}
};