generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem42.cs
More file actions
47 lines (39 loc) · 1.16 KB
/
Problem42.cs
File metadata and controls
47 lines (39 loc) · 1.16 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
namespace LeetCode;
using System.Text;
/// <summary>
/// <see href="https://leetcode.com/problems/valid-anagram/">Valid Anagram</see>.
/// </summary>
public static class Problem42
{
/// <summary>
/// Given two strings s and t, return true if t is an anagram of s, and false otherwise.
/// Time complexity: O(s + t).
/// Space complexity: O(1).
/// </summary>
/// <param name="s">String s.</param>
/// <param name="t">String t.</param>
/// <returns>True, if the second string is an anagram of the first.</returns>
public static bool IsAnagram(string s, string t)
{
var sKey = GenerateKey(s);
var tKey = GenerateKey(t);
return sKey == tKey;
}
private static string GenerateKey(string str)
{
var alphabet = new int[26];
foreach (var character in str)
{
alphabet[character - 'a']++;
}
var sb = new StringBuilder();
for (var i = 0; i < alphabet.Length; i++)
{
if (alphabet[i] != 0)
{
sb = sb.Append(alphabet[i]).Append((char)(i + 'a'));
}
}
return sb.ToString();
}
}