Compare commits

..

16 Commits

44 changed files with 2170 additions and 416 deletions

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_10._Regular_Expression_Matching</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,29 @@
var solution = new Solution();
var examples = new (string s, string p, bool expected)[]
{
("aa", "a", false),
("aa", "a*", true),
("ab", ".*", true),
("aab", "c*a*b", true),
("mississippi", "mis*is*p*.", false),
("mississippi", "mis*is*ip*.", true),
("aaa", "a*a", true),
("aaa", "ab*a*c*a", true),
("ab", ".*c", false),
("", "c*", true),
("abcd", "d*", false),
("", "", true),
("a", ".", true),
("", "a*", true),
("aa", "b*a*", true),
("a", "ab*", true),
("abcaaaaaaabaabcabac", ".*ab.a.*a*a*.*b*b*", true),
("", "a*b*", true),
};
foreach (var example in examples)
{
var result = solution.IsMatch(example.s, example.p);
Console.WriteLine($"s = \"{example.s}\", p = \"{example.p}\" => {result} (expected {example.expected})");
}

View File

@@ -0,0 +1,59 @@
public class Solution
{
public bool IsMatch(string s, string p) => IsMatch(null, s, p);
private bool IsMatch(char? prev, ReadOnlySpan<char> str, ReadOnlySpan<char> pattern)
{
if (pattern.Length == 0 && str.Length == 0)
return true;
if (str.Length == 0)
{
if (CanBeEmpty(pattern))
return true;
return false;
}
if (pattern.Length == 0)
return false;
var sym = str[0];
var p = pattern[0];
// раскрытая звёздочка
var pSymOrDot = p == '*' ? prev : p; // превращаем звёздочку в символ или точку
// ожидаемый текущий символ, конкретный
var pSym = pSymOrDot == '.' ? sym : pSymOrDot;
// следующий символ *
if (pattern.Length > 1 && pattern[1] == '*')
{
var match = false;
var i = 0;
do
{
match |= IsMatch(i > 0 ? p : prev, str[i..], pattern[2..]);
if (match || i == str.Length || str[i] != p && p != '.')
break;
i++;
}
while (i <= str.Length);
return match;
}
else if (sym != pSym)
{
return false;
}
else
{
return IsMatch(pSymOrDot, str[1..], pattern[1..]);
}
}
private bool CanBeEmpty(ReadOnlySpan<char> pattern)
{
if (pattern.Length % 2 == 1)
return false;
for (var i = 1; i < pattern.Length; i += 2)
if (pattern[i] != '*')
return false;
return true;
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_114._Flatten_Binary_Tree_to_Linked_List</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,67 @@
var sol = new Solution();
var cases = new (int?[] input, int?[] expected)[]
{
(new int?[] { 1, 2, 5, 3, 4, null, 6 }, new int?[] { 1, null, 2, null, 3, null, 4, null, 5, null, 6 }),
// (Array.Empty<int?>(), Array.Empty<int?>()),
// (new int?[] { 0 }, new int?[] { 0 })
};
foreach (var (input, expected) in cases)
{
var root = BuildTreeFromLevelOrder(input);
if (root != null)
sol.Flatten(root);
var actual = FlattenToOutputList(root);
Console.WriteLine($"[{string.Join(", ", input.Select(FormatNullable))}] -> [{string.Join(", ", actual.Select(FormatNullable))}] (expected: [{string.Join(", ", expected.Select(FormatNullable))}])");
}
static TreeNode? BuildTreeFromLevelOrder(int?[] data)
{
if (data.Length == 0 || data[0] == null)
return null;
var root = new TreeNode(data[0]!.Value);
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
var i = 1;
while (queue.Count > 0 && i < data.Length)
{
var node = queue.Dequeue();
if (i < data.Length && data[i] != null)
{
node.left = new TreeNode(data[i]!.Value);
queue.Enqueue(node.left);
}
i++;
if (i < data.Length && data[i] != null)
{
node.right = new TreeNode(data[i]!.Value);
queue.Enqueue(node.right);
}
i++;
}
return root;
}
static List<int?> FlattenToOutputList(TreeNode? root)
{
var result = new List<int?>();
var node = root;
while (node != null)
{
result.Add(node.val);
if (node.right != null)
result.Add(null);
node = node.right;
}
return result;
}
static string FormatNullable(int? value) => value?.ToString() ?? "null";

View File

@@ -0,0 +1,27 @@
public class Solution
{
public void Flatten(TreeNode? root)
{
if (root == null)
return;
var head = root;
var stack = new Stack<TreeNode>();
if (root.right != null)
stack.Push(root.right);
if (root.left != null)
stack.Push(root.left);
while (stack.Count > 0)
{
var node = stack.Pop();
head.left = null;
head.right = node;
head = node;
if (node.right != null)
stack.Push(node.right);
if (node.left != null)
stack.Push(node.left);
}
}
}

View File

@@ -0,0 +1,12 @@
public class TreeNode
{
public int val;
public TreeNode? left;
public TreeNode? right;
public TreeNode(int val = 0, TreeNode? left = null, TreeNode? right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}

View File

@@ -1,8 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<RootNamespace>_18._4Sum</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>

40
18. 4Sum/Program.cs Normal file
View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
var sol = new Solution();
var cases = new (int[] nums, int target, int[][] expected)[]
{
// (new[] { 1, 0, -1, 0, -2, 2 }, 0, new[]
// {
// new[] { -2, -1, 1, 2 },
// new[] { -2, 0, 0, 2 },
// new[] { -1, 0, 0, 1 }
// }),
// (new[] { 2, 2, 2, 2, 2 }, 8, new[]
// {
// new[] { 2, 2, 2, 2 }
// }),
// (new[] { -3, -1, 0, 2, 4, 5 }, 2, new[]
// {
// new[] { -3, -1, 2, 4 }
// }),
(new[] { 1000000000, 1000000000, 1000000000, 1000000000 }, -294967296, Array.Empty<int[]>())
};
foreach (var (nums, target, expected) in cases)
{
var actual = sol.FourSum(nums, target);
Console.WriteLine($"nums={FormatArray(nums)}, target={target} -> {FormatResults(actual)} (expected: {FormatResults(expected)})");
}
static string FormatArray(int[] nums)
{
return $"[{string.Join(",", nums)}]";
}
static string FormatResults(IList<IList<int>> results)
{
return "[" + string.Join(",", results.Select(r => $"[{string.Join(",", r)}]")) + "]";
}

143
18. 4Sum/Solution.cs Normal file
View File

@@ -0,0 +1,143 @@
public class Solution
{
record struct TwoSumSource(int A, int B)
{
public override string ToString()
{
return $"({A}+{B}={A + B})";
}
}
record struct AnswerRow(int? N0 = null, int? N1 = null, int? N2 = null, int? N3 = null)
{
public void PushNum(int num)
{
if (N0 == null)
{
N0 = num;
}
else if (N1 == null)
{
N1 = num;
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
else if (N2 == null)
{
N2 = num;
if (N1 > N2)
{
(N1, N2) = (N2, N1);
}
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
else if (N3 == null)
{
N3 = num;
if (N2 > N3)
{
(N2, N3) = (N3, N2);
}
if (N1 > N2)
{
(N1, N2) = (N2, N1);
}
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
else if (num < N3)
{
N3 = num;
if (N2 > N3)
{
(N2, N3) = (N3, N2);
}
if (N1 > N2)
{
(N1, N2) = (N2, N1);
}
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
}
}
public IList<IList<int>> FourSum(int[] nums, int target)
{
var dict = new Dictionary<int, int>();
// суммы из двух слагаемых, все возможные
var twoSums = new Dictionary<long, HashSet<TwoSumSource>>();
for (var i = 0; i < nums.Length; i++)
{
var num1 = nums[i];
dict.TryAdd(num1, 0);
dict[num1]++;
for (var j = i + 1; j < nums.Length; j++)
{
var num2 = nums[j];
var sum = num1 + num2;
twoSums.TryAdd(sum, new HashSet<TwoSumSource>());
twoSums[sum].Add(new TwoSumSource() { A = num1, B = num2 });
}
}
var rows = new HashSet<AnswerRow>();
// словарь для требуемоего количества чисел
var needDict = new Dictionary<int, int>();
foreach (var kp1 in dict)
{
var needThreeSum = target - kp1.Key;
needDict.TryAdd(kp1.Key, 0);
needDict[kp1.Key]++;
foreach (var kp2 in dict)
{
needDict.TryAdd(kp2.Key, 0);
needDict[kp2.Key]++;
var needTwoSum = (long)needThreeSum - kp2.Key;
if (twoSums.TryGetValue(needTwoSum, out var curTwoSums))
{
foreach (var curTwoSum in curTwoSums)
{
needDict.TryAdd(curTwoSum.A, 0);
needDict[curTwoSum.A]++;
needDict.TryAdd(curTwoSum.B, 0);
needDict[curTwoSum.B]++;
if (needDict.All(kp => dict[kp.Key] >= kp.Value))
{
var row = new AnswerRow();
row.PushNum(kp1.Key);
row.PushNum(kp2.Key);
row.PushNum(curTwoSum.A);
row.PushNum(curTwoSum.B);
rows.Add(row);
}
needDict[curTwoSum.A]--;
needDict[curTwoSum.B]--;
}
}
needDict[kp2.Key]--;
}
needDict.Clear();
}
var answer = new List<IList<int>>(rows.Count);
foreach (var row in rows)
answer.Add(new List<int> { row.N0!.Value, row.N1!.Value, row.N2!.Value, row.N3!.Value });
return answer;
}
}

View File

@@ -1,7 +1,7 @@
namespace _2._Add_Two_Numbers; namespace _2._Add_Two_Numbers;
public class Solution { public class Solution {
public ListNode AddTwoNumbers(ListNode? l1, ListNode? l2) public ListNode? AddTwoNumbers(ListNode? l1, ListNode? l2)
{ {
ListNode? answer = null; ListNode? answer = null;
ListNode? answerEnd = answer; ListNode? answerEnd = answer;
@@ -24,7 +24,7 @@ public class Solution {
toNext = sum / 10; toNext = sum / 10;
sum %= 10; sum %= 10;
ListNode item = new ListNode(sum); ListNode item = new ListNode(sum);
if (answer == null) if (answer == null || answerEnd == null)
answer = answerEnd = item; answer = answerEnd = item;
else else
{ {
@@ -33,7 +33,7 @@ public class Solution {
} }
} }
if (toNext != 0) if (toNext != 0 && answerEnd != null)
answerEnd.next = new ListNode(toNext); answerEnd.next = new ListNode(toNext);
return answer; return answer;
} }

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_23._Merge_k_Sorted_Lists</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,11 @@
public class ListNode
{
public int val;
public ListNode? next;
public ListNode(int val = 0, ListNode? next = null)
{
this.val = val;
this.next = next;
}
}

View File

@@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

View File

@@ -0,0 +1,29 @@
public class Solution
{
public ListNode? MergeKLists(ListNode[] lists)
{
ListNode? head = null;
ListNode? tail = null;
var queue = new PriorityQueue<ListNode, int>();
foreach (var l in lists)
if (l != null)
queue.Enqueue(l, l.val);
while (queue.Count > 0)
{
var l = queue.Dequeue();
if (head == null || tail == null)
{
head = l;
tail = l;
}
else
{
tail.next = l;
tail = l;
}
if (l.next != null)
queue.Enqueue(l.next, l.next.val);
}
return head;
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_26._Remove_Duplicates_from_Sorted_Array</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

View File

@@ -0,0 +1,16 @@
public class Solution {
public int RemoveDuplicates(int[] nums) {
var k = nums.Length;
var putIndex = 0;
for(var i = 0; i < nums.Length; i++)
{
while(i < nums.Length - 1 && nums[i+1] == nums[i])
{
i++;
k--;
}
nums[putIndex++] = nums[i];
}
return k;
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_2906._Construct_Product_Matrix</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,74 @@
static string FormatMatrix(int[][] matrix)
{
var rows = new string[matrix.Length];
for (var i = 0; i < matrix.Length; i++)
rows[i] = "[" + string.Join(",", matrix[i]) + "]";
return "[" + string.Join(",", rows) + "]";
}
var sol = new Solution();
var cases = new (int[][] input, string expected)[]
{
(
new[]
{
new[] { 1, 2 },
new[] { 3, 4 }
},
"[[24,12],[8,6]]"
),
(
new[]
{
new[] { 12345 },
new[] { 2 },
new[] { 1 }
},
"[[2],[0],[0]]"
),
(
new[]
{
new[] { 4, 8, 8 },
new[] { 6, 2, 5 },
new[] { 7, 3, 7 },
new[] { 6, 3, 5 }
},
"[[3525,7935,7935],[6465,7050,2820],[7305,585,7305],[6465,585,2820]]"
),
(
new[]
{
new[] { 4, 3, 9 },
new[] { 3, 9, 10 },
new[] { 9, 7, 8 },
new[] { 8, 4, 7 },
new[] { 6, 1, 3 }
},
"[[3255,225,75],[225,75,11178],[75,1860,7800],[7800,3255,1860],[6285,675,225]]"
),
(
new[]
{
new []{1,2,2},
new []{1,4,3}
},
"[[48,24,24],[48,12,16]]"
),
(
new[]
{
new[] { 414750857 },
new[] { 449145368 },
new[] { 767292749 }
},
"[[1462],[3103],[9436]]"
)
};
foreach (var (input, expected) in cases)
{
var actual = sol.ConstructProductMatrix(input);
Console.WriteLine($"{FormatMatrix(input)} -> {FormatMatrix(actual)} (expected: {expected})");
}

View File

@@ -0,0 +1,80 @@
public class Solution
{
struct MulInfo
{
public long Left;
public long Right;
}
public int[][] ConstructProductMatrix(int[][] grid)
{
var mod = 12345;
var table = new MulInfo[grid.Length][];
var lastRow = grid.Length - 1;
var lastCol = grid[0].Length - 1;
// прямой проход
for (var i = 0; i < grid.Length; i++)
{
table[i] = new MulInfo[grid[i].Length];
for (var j = 0; j < grid[i].Length; j++)
{
if (j == 0 && i == 0)
{
table[i][j].Left = grid[i][j] % mod;
}
else if (j > 0)
{
table[i][j].Left = table[i][j - 1].Left * grid[i][j] % mod;
}
else if (i > 0)
{
table[i][j].Left = table[i - 1][lastCol].Left * grid[i][j];
table[i][j].Left %= mod;
}
}
}
// обратный проход
for (var i = lastRow; i >= 0; i--)
{
for (var j = lastCol; j >= 0; j--)
{
if (j == lastCol && i == lastRow)
{
table[i][j].Right = grid[i][j] % mod;
}
else if (j < lastCol)
{
table[i][j].Right = table[i][j + 1].Right * grid[i][j] % mod;
}
else if (i < lastRow)
{
table[i][j].Right = table[i + 1][0].Right * grid[i][j] % mod;
}
var left = 1L;
var right = 1L;
if (i == 0 && j == 0)
left = 1;
else if (j > 0)
left = table[i][j - 1].Left;
else if (i > 0)
left = table[i - 1][lastCol].Left;
if (i == lastRow && j == lastCol)
right = 1;
else if (j < lastCol)
right = table[i][j + 1].Right;
else if (i < lastRow)
right = table[i + 1][0].Right;
grid[i][j] = (int)(left * right % mod);
}
}
return grid;
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_30._Substring_with_Concatenation_of_All_Words</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,18 @@
var sol = new Solution();
var cases = new (string s, string[] words, int[] expected)[]
{
// ("barfoothefoobarman", new[] { "foo", "bar" }, new[] { 0, 9 }),
// ("wordgoodgoodgoodbestword", new[] { "word", "good", "best", "word" }, Array.Empty<int>()),
// ("barfoofoobarthefoobarman", new[] { "bar", "foo", "the" }, new[] { 6, 9, 12 }),
("wordgoodgoodgoodbestword", new[] { "word", "good", "best", "good" }, new[] { 8 })
};
string Format(IEnumerable<int> values) => $"[{string.Join(",", values)}]";
string FormatWords(IEnumerable<string> values) => $"[{string.Join(",", values)}]";
foreach (var (s, words, expected) in cases)
{
var actual = sol.FindSubstring(s, words);
Console.WriteLine($"{s} | {FormatWords(words)} -> {Format(actual)} (expected: {Format(expected)})");
}

View File

@@ -0,0 +1,35 @@
public class Solution
{
public IList<int> FindSubstring(string s, string[] words)
{
var len = words[0].Length;
var allLen = len * words.Length;
var dict = new Dictionary<string, int>();
foreach (var word in words)
{
dict.TryAdd(word, 0);
dict[word]++;
}
var answer = new List<int>();
var windowDict = new Dictionary<string, int>();
for (var offset = 0; offset < len; offset++)
{
for (var i = offset; i <= s.Length-len; i += len)
{
var word = s[i..(i + len)];
var prevInx = i - allLen;
if (prevInx >= 0)
{
var leftWord = s[prevInx..(prevInx + len)];
windowDict[leftWord]--;
}
windowDict.TryAdd(word, 0);
windowDict[word]++;
if (dict.All(kvp => windowDict.TryGetValue(kvp.Key, out var count) && count == kvp.Value))
answer.Add(prevInx + len);
}
windowDict.Clear();
}
return answer;
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_31._Next_Permutation</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,30 @@
var sol = new Solution();
var cases = new (int[] input, int[] expected)[]
{
(new[] { 1, 2, 3 }, new[] { 1, 3, 2 }),
(new[] { 3, 2, 1 }, new[] { 1, 2, 3 }),
(new[] { 1, 1, 5 }, new[] { 1, 5, 1 })
};
foreach (var (input, expected) in cases)
{
var nums = (int[])input.Clone();
sol.NextPermutation(nums);
var status = AreEqual(nums, expected) ? "ok" : "fail";
Console.WriteLine($"{Format(input)} -> {Format(nums)} (expected: {Format(expected)}) {status}");
}
static string Format(int[] nums) => $"[{string.Join(",", nums)}]";
static bool AreEqual(int[] left, int[] right)
{
if (left.Length != right.Length)
return false;
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
return false;
}
return true;
}

View File

@@ -0,0 +1,17 @@
public class Solution
{
public void NextPermutation(int[] nums)
{
var i = nums.Length - 2;
while(i >= 0 && nums[i] >= nums[i+1])
i--;
if(i >= 0)
{
var j = nums.Length - 1;
while(nums[i] >= nums[j])
j--;
(nums[i], nums[j]) = (nums[j], nums[i]);
}
Array.Reverse(nums, i+1, nums.Length-i-1);
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_32._Longest_Valid_Parentheses</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,5 @@
var sol = new Solution();
// System.Console.WriteLine(sol.LongestValidParentheses(")()())"));
// System.Console.WriteLine(sol.LongestValidParentheses("()(()"));
System.Console.WriteLine(sol.LongestValidParentheses("()(())"));

View File

@@ -0,0 +1,43 @@
public class Solution
{
struct Item
{
public char Sym;
public int Count;
public char? PrevSym;
}
public int LongestValidParentheses(string s)
{
var stack = new Stack<Item>();
var answer = 0;
foreach (var ch in s)
{
if (stack.Count > 0 && (stack.Peek().Sym == '(' || stack.Peek().PrevSym == '(') && ch == ')')
{
var prev = stack.Pop();
var count = 2;
if (prev.Sym == '#')
{
stack.Pop();
count += prev.Count;
}
while (stack.Count > 0 && stack.Peek().Sym == '#')
count += stack.Pop().Count;
char? prevSym = null;
if (stack.Count > 0)
prevSym = stack.Peek().Sym;
stack.Push(new Item() { Sym = '#', Count = count, PrevSym = prevSym });
answer = Math.Max(answer, count);
}
else
{
stack.Push(new Item() { Sym = ch, Count = 0 });
}
}
return answer;
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_3546._Equal_Sum_Grid_Partition_I</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,29 @@
var sol = new Solution();
var cases = new (int[][] grid, bool expected, string name)[]
{
(
new[]
{
new[] { 1, 4 },
new[] { 2, 3 }
},
true,
"Example 1"
),
(
new[]
{
new[] { 1, 3 },
new[] { 2, 4 }
},
false,
"Example 2"
)
};
foreach (var (grid, expected, name) in cases)
{
var actual = sol.CanPartitionGrid(grid);
Console.WriteLine($"{name}: {actual} (expected: {expected})");
}

View File

@@ -0,0 +1,49 @@
public class Solution
{
struct SumInfo
{
public long Left;
public long Right;
public long Value;
}
public bool CanPartitionGrid(int[][] grid)
{
var height = grid.Length;
var width = grid[0].Length;
var colSums = new SumInfo[width];
var rowSums = new SumInfo[height];
for (var i = 0; i < height; i++)
{
for (var j = 0; j < grid[i].Length; j++)
{
colSums[j].Value += grid[i][j];
rowSums[i].Value += grid[i][j];
}
rowSums[i].Left = rowSums[i].Value;
if (i > 0)
rowSums[i].Left += rowSums[i - 1].Left;
}
for (var i = height - 1; i >= 0; i--)
{
rowSums[i].Right = rowSums[i].Value;
if (i < height - 1)
rowSums[i].Right += rowSums[i + 1].Right;
}
for (var j = 0; j < width; j++)
{
colSums[j].Left = colSums[j].Value;
if (j > 0)
colSums[j].Left += colSums[j - 1].Left;
}
for (var j = width - 1; j >= 0; j--)
{
colSums[j].Right = colSums[j].Value;
if (j < width - 1)
colSums[j].Right += colSums[j + 1].Right;
}
return rowSums.Any(row => Math.Abs(row.Left - row.Right) == row.Value) || colSums.Any(col => Math.Abs(col.Left - col.Right) == col.Value);
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_3548._Equal_Sum_Grid_Partition_II</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,139 @@
var sol = new Solution();
var cases = new (int[][] grid, bool expected, string name)[]
{
(
new[]
{
new[] { 1, 4 },
new[] { 2, 3 }
},
true,
"Example 1"
),
(
new[]
{
new[] { 1, 2 },
new[] { 3, 4 }
},
true,
"Example 2"
),
(
new[]
{
new[] { 1, 2, 4 },
new[] { 2, 3, 5 }
},
false,
"Example 3"
),
(
new[]
{
new[] { 4, 1, 8 },
new[] { 3, 2, 6 }
},
false,
"Example 4"
),
(
new[]
{
new[] { 5, 5, 6, 2, 2, 2 }
},
true,
"Example 5"
),
(
new[]
{
new[] { 100000 },
new[] { 86218 },
new[] { 100000 }
},
true,
"Example 6"
),
(
new[]
{
new[] { 1, 2, 4 },
new[] { 1, 6, 6 },
new[] { 5, 6, 7 }
},
true,
"Example 7"
),
(
new[]
{
new[] { 1, 2, 1, 1, 1 },
new[] { 1, 1, 1, 2, 1 }
},
true,
"Example 8"
),
(
new[]
{
new[] { 1, 1 },
new[] { 2, 1 },
new[] { 1, 1 },
new[] { 1, 2 },
new[] { 1, 1 }
},
true,
"Example 9"
),
(
new[]
{
new[] { 10, 5, 4, 5 }
},
false,
"Example 10"
),
(
new[]
{
new[] { 1, 1 },
new[] { 2, 1 },
new[] { 4, 3 }
},
false,
"Example 11"
),
(
new[]
{
new[] { 4 },
new[] { 3 },
new[] { 4 },
new[] { 4 },
new[] { 4 }
},
false,
"Example 12"
),
(
new[]
{
new[] { 100000 },
new[] { 100000 },
new[] { 100000 },
new[] { 100000 },
new[] { 1 }
},
true,
"Example 13"
),
};
foreach (var (grid, expected, name) in cases)
{
var actual = sol.CanPartitionGrid(grid);
Console.WriteLine($"{name}: {actual} (expected: {expected})");
}

View File

@@ -0,0 +1,130 @@
public class Solution
{
struct SumInfo
{
public long Left;
public long Right;
public long Value;
// ключ - число, значение - индексы, где оно встречается
public Dictionary<long, SortedSet<int>> Nums;
}
public bool CanPartitionGrid(int[][] grid)
{
var height = grid.Length;
var width = grid[0].Length;
var colSums = new SumInfo[width];
var rowSums = new SumInfo[height];
for (var i = 0; i < height; i++)
{
for (var j = 0; j < width; j++)
{
var num = grid[i][j];
colSums[j].Value += num;
rowSums[i].Value += num;
rowSums[i].Nums ??= new Dictionary<long, SortedSet<int>>();
colSums[j].Nums ??= new Dictionary<long, SortedSet<int>>();
rowSums[i].Nums.TryAdd(num, new SortedSet<int>());
rowSums[i].Nums[num].Add(j);
colSums[j].Nums.TryAdd(num, new SortedSet<int>());
colSums[j].Nums[num].Add(i);
}
rowSums[i].Left = rowSums[i].Value;
if (i > 0)
rowSums[i].Left += rowSums[i - 1].Left;
}
for (var i = height - 1; i >= 0; i--)
{
rowSums[i].Right = rowSums[i].Value;
if (i < height - 1)
rowSums[i].Right += rowSums[i + 1].Right;
}
for (var j = 0; j < width; j++)
{
colSums[j].Left = colSums[j].Value;
if (j > 0)
colSums[j].Left += colSums[j - 1].Left;
}
for (var j = width - 1; j >= 0; j--)
{
colSums[j].Right = colSums[j].Value;
if (j < width - 1)
colSums[j].Right += colSums[j + 1].Right;
}
var answer = false;
for (var i = 0; i < rowSums.Length - 1 && !answer; i++)
{
var row = rowSums[i];
var nextRow = rowSums[i + 1];
var diff = Math.Abs(row.Left - nextRow.Right);
var edgesOnly = colSums.Length == 1;
var colLen = height;
if (diff == 0 ||
(row.Left < nextRow.Right && CanDelete(diff, colSums, i, true, i + 1 == rowSums.Length - 1, edgesOnly, colLen)) ||
(row.Left > nextRow.Right && CanDelete(diff, colSums, i, false, i == 0, edgesOnly, colLen)))
answer |= true;
}
for (var j = 0; j < colSums.Length - 1 && !answer; j++)
{
var col = colSums[j];
var nextCol = colSums[j + 1];
var diff = Math.Abs(col.Left - nextCol.Right);
// тут проход по колонкам, значит поиск элемента для удаления надо выполнять по строкам
// если j == 0 и отрезаем в левой части, то надо смотреть только первую и последнюю строку
// если j+1 == colSums.Len-1 и отрезаем в правой части, то надо смотреть только первую и последнюю строку
var edgesOnly = rowSums.Length == 1;
var rowLen = width;
if (diff == 0 ||
(col.Left < nextCol.Right && CanDelete(diff, rowSums, j, true, j + 1 == colSums.Length - 1, edgesOnly, rowLen)) ||
(col.Left > nextCol.Right && CanDelete(diff, rowSums, j, false, j == 0, edgesOnly, rowLen)))
answer |= true;
}
return answer;
}
/// <summary>
///
/// </summary>
/// <param name="target">Целевое число для поиска</param>
/// <param name="infos">Что перебирать</param>
/// <param name="idx">Индекс отсечения (для удаления справа строго больше, для удаления слева включительно)</param>
/// <param name="deleteAfterIdx">Удалять ли спарва от индекса</param>
/// <param name="firstAndLastOnly">Посмотреть только первый и последний SumInfo</param>
/// <param name="edgesOnly">В sumInfo брать только крайние элементы</param>
/// <param name="len">Количество чисел в SumInfo</param>
/// <returns></returns>
private static bool CanDelete(long target, SumInfo[] infos, int idx, bool deleteAfterIdx, bool firstAndLastOnly, bool edgesOnly, int len)
{
for (var i = 0; i < infos.Length; i++)
{
var nums = infos[i].Nums;
if (nums.TryGetValue(target, out var indexes))
{
var before = false;
var after = false;
if (edgesOnly)
{
before = indexes.Contains(0) || indexes.Contains(idx);
after = indexes.Contains(len - 1) || indexes.Contains(idx+1);
}
else
{
before = indexes.GetViewBetween(int.MinValue, idx).Count > 0;
after = indexes.GetViewBetween(idx + 1, int.MaxValue).Count > 0;
}
if ((before && !deleteAfterIdx) || (after && deleteAfterIdx))
return true;
}
// если только границы, перейти сразу к последнему элементу
if (firstAndLastOnly && i == 0)
i = Math.Max(i, infos.Length - 2);
}
return false;
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_5._Longest_Palindromic_Substring</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,18 @@
var sol = new Solution();
var cases = new (string input, string expected)[]
{
("babad", "bab"),
("cbbd", "bb"),
("a", "a"),
("ac", "a"),
("forgeeksskeegfor", "geeksskeeg"),
("abba", "abba"),
("racecar", "racecar")
};
foreach (var (input, expected) in cases)
{
var actual = sol.LongestPalindrome(input);
Console.WriteLine($"{input} -> {actual} (expected: {expected})");
}

View File

@@ -0,0 +1,56 @@
using System.Text;
public class Solution
{
public string LongestPalindrome(string s)
{
if (string.IsNullOrEmpty(s))
return "";
var str = PrepareString(s);
var radii = new int[str.Length];
var set = new HashSet<int>(); // Индексы радиусов для обработки
var answer = string.Empty;
for (var i = 0; i < str.Length; i++)
{
var sym = str[i];
var toRemove = new List<int>();
foreach (var radiusIdx in set)
{
var new_radius = radii[radiusIdx] + 1;
// Если с новым радиусом выходим за границы
if (radiusIdx - new_radius < 0 || radiusIdx + new_radius >= str.Length || str[radiusIdx - new_radius] != sym)
{
var len = radii[radiusIdx] * 2 + 1;
if (len > answer.Length)
answer = str.Substring(radiusIdx - radii[radiusIdx], len);
toRemove.Add(radiusIdx);
}
else
radii[radiusIdx] = new_radius;
}
foreach (var removeIdx in toRemove)
set.Remove(removeIdx);
set.Add(i);
}
foreach (var radiusIdx in set)
{
var len = radii[radiusIdx] * 2 + 1;
if (len > answer.Length || answer == "#")
answer = str.Substring(radiusIdx - radii[radiusIdx], len);
}
return answer.Replace("#", "");
}
public string PrepareString(string s)
{
var sb = new StringBuilder();
sb.Append('#');
foreach (var ch in s)
sb.Append($"{ch}#");
return sb.ToString();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto

398
Leetcode/.gitignore vendored
View File

@@ -1,398 +0,0 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml

View File

@@ -1,10 +0,0 @@
namespace Leetcode
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}

22
create_project.sh Normal file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 1 ]]; then
echo "Usage: $0 \"Project Name\""
exit 1
fi
project_name="$1"
if [[ -z "$project_name" ]]; then
echo "Project name cannot be empty"
exit 1
fi
if [[ -d "$project_name" ]]; then
echo "Directory already exists: $project_name"
exit 1
fi
dotnet new console -n "$project_name"
dotnet sln add "$project_name"