-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution859.cs
61 lines (54 loc) · 1.31 KB
/
Solution859.cs
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
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution859
{
/// <summary>
/// 859. Buddy Strings - Easy
/// <a href="https://leetcode.com/problems/buddy-strings">See the problem</a>
/// </summary>
public bool BuddyStrings(string s, string goal)
{
if (s.Length != goal.Length)
{
return false;
}
if (s == goal)
{
int[] count = new int[26];
foreach (char c in s)
{
count[c - 'a']++;
}
foreach (int c in count)
{
if (c > 1)
{
return true;
}
}
return false;
}
int first = -1;
int second = -1;
for (int i = 0; i < s.Length; i++)
{
if (s[i] != goal[i])
{
if (first == -1)
{
first = i;
}
else if (second == -1)
{
second = i;
}
else
{
return false;
}
}
}
return second != -1 && s[first] == goal[second] && s[second] == goal[first];
}
}