-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution1.cs
More file actions
82 lines (72 loc) · 2.44 KB
/
Solution1.cs
File metadata and controls
82 lines (72 loc) · 2.44 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
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cSharpSolutions
{
internal class Solution1
{
// Basic approach: loops through string
public static char? FirstNonRepeatingChar(string input)
{
for (int i = 0; i < input.Length; i++)
{
bool repeated = false;
for (int j = 0; j < input.Length; j++)
{
if (i != j && input[i] == input[j])
{
repeated = true;
break;
}
}
if (!repeated)
return input[i];
}
return null; // no non-repeating character found
}
// Optimized approach using Dictionary
public static char? FirstNonRepeatingCharOptimized(string input)
{
var countDict = new Dictionary<char, int>();
foreach (var c in input)
{
if (countDict.ContainsKey(c))
countDict[c]++;
else
countDict[c] = 1;
}
foreach (var c in input)
{
if (countDict[c] == 1)
return c;
}
return null;
}
// Run method for console testing
public static void Run()
{
Console.WriteLine("=== Solution 1: First Non-Repeating Character ===");
string[] testCases =
{
"aabccdeff", // Expected: b
"aabbcc", // Expected: null
"abcdef", // Expected: a
"mmalawi", // Expected: l
"zzxxyy", // Expected: null
"lacsonimran", // Expected: l
"llaccssooniimmran" // Expected: r
};
foreach (var test in testCases)
{
var basic = FirstNonRepeatingChar(test);
var optimized = FirstNonRepeatingCharOptimized(test);
Console.WriteLine($"\nInput: \"{test}\"");
Console.WriteLine($" Basic: {(basic != null ? basic.ToString() : "null")}");
Console.WriteLine($" Optimized: {(optimized != null ? optimized.ToString() : "null")}");
}
Console.WriteLine("\nSolution 1 complete");
}
}
}