Skip to content

Commit 5da98c3

Browse files
committed
Good question with lots of edge cases, nice
1 parent 45e4acf commit 5da98c3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

859. Buddy Strings.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
bool buddyStrings(string s, string goal)
4+
{
5+
if(s.length()!=goal.length())
6+
{
7+
return false;
8+
}
9+
if(s==goal)
10+
{
11+
vector<int> count(26,0);
12+
13+
for(auto x: s)
14+
{
15+
count[x-'a']++;
16+
if(count[x-'a']==2)
17+
{
18+
return true;
19+
}
20+
}
21+
return false;
22+
}
23+
vector<int> ans;
24+
for(int i = 0;i<s.length();i++)
25+
{
26+
if(s[i]!=goal[i])
27+
{
28+
ans.push_back(i);
29+
}
30+
if(ans.size()>2)
31+
{
32+
return false;
33+
}
34+
}
35+
36+
return ans.size()==2&&s[ans[0]]==goal[ans[1]] && s[ans[1]]==goal[ans[0]];
37+
}
38+
};

0 commit comments

Comments
 (0)