-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
47 lines (45 loc) · 1.08 KB
/
Solution.cs
File metadata and controls
47 lines (45 loc) · 1.08 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
public class Solution
{
public int LongestSubsequence(string s, int k)
{
string binaryK = IntToBinary(k);
int ret = 1;
for (int i = 1; i <= s.Length; i++)
{
ret = Math.Max(ret, LongestSubsequence(s[..i], binaryK));
}
return ret;
}
string IntToBinary(int n)
{
StringBuilder sb = new();
while (n > 0)
{
sb.Append(n & 1);
n >>= 1;
}
char[] tmp = sb.ToString().ToArray();
Array.Reverse(tmp);
return new(tmp);
}
int LongestSubsequence(string a, string b)
{
if (a.Length < b.Length) return a.Length;
int remain = a.Length - b.Length;
int count = 0;
for (int i = 0; i < remain; i++)
{
if (a[i] == '0') count++;
}
for (int i = 0; i < b.Length; i++)
{
if (a[remain + i] - b[i] < 0) break;
if (a[remain + i] - b[i] > 0)
{
count--;
break;
}
}
return count + b.Length;
}
}