# Algo. Buddy Strings

https://leetcode.com/problems/buddy-strings/

``````/* main idea is to search unmatched symbols, and it shoeld be only 2 of them to swap */

public class Solution {
public bool BuddyStrings(string s, string goal)
{
if (s.Length != goal.Length)
return false;

if (s.Equals(goal))
{
if (IsDublicateSymbol(s))
return true;
return false;
}

var unmatched = 0;
var sbSource = new StringBuilder();
var sbGoal = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (s[i] != goal[i])
{
if (unmatched > 2)
return false;

unmatched++;
sbSource.Append(s[i]);
sbGoal.Append(goal[i]);
}
}

if (unmatched == 2)
{
if (ReverseString(sbSource.ToString()) == sbGoal.ToString())
return true;
}
else return false;

return false;
}

bool IsDublicateSymbol(string s)
{
var hashSet = new HashSet<char>();
foreach (var c in s)
{
if (hashSet.Add(c) == false)
return true;
}

return false;
}

string ReverseString(string s)
{
var ca = s.ToCharArray();
Array.Reverse(ca);
return new string(ca);
}
}``````
This entry was posted in Без рубрики. Bookmark the permalink.