-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlongest_palindrome.dart
147 lines (111 loc) · 2.59 KB
/
longest_palindrome.dart
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
-* 409. Longest Palindrome *-
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
Example 1:
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Example 2:
Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.
Constraints:
1 <= s.length <= 2000
s consists of lowercase and/or uppercase English letters only.
*/
class Solution {
int longestPalindrome(String s) {
Map<String, int> frequency = {};
int length = 0;
// Count the frequency of each letter
for (int i = 0; i < s.length; i++) {
String char = s[i];
frequency[char] = (frequency[char] ?? 0) + 1;
}
// Iterate through the frequency counts
frequency.values.forEach((count) {
if (count % 2 == 0) {
length += count;
} else {
length += count - 1;
}
});
// Check for remaining letters with odd counts
if (length < s.length) {
length += 1;
}
return length;
}
}
class B {
int longestPalindrome(String s) {
List<int> count = List<int>.filled(256, 0);
int odds = 0;
for (int i = 0; i < s.length; i++) {
int char = s.codeUnitAt(i);
count[char]++;
if (count[char] % 2 == 1) {
odds++;
} else {
odds--;
}
}
return s.length - odds + boolToInt(odds > 0);
}
int boolToInt(bool b) {
return b ? 1 : 0;
}
}
class C {
int longestPalindrome(String s) {
int dp = s.runes.fold(0, (int acc, int x) {
acc ^= 1 << (x - 65);
return acc;
});
return s.length - countSetBits(dp) + (dp != 0 ? 1 : 0);
}
int countSetBits(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>= 1;
}
return count;
}
}
class BitSet {
int _value;
BitSet() : _value = 0;
void flip(int k) {
_value ^= (1 << k);
}
bool get(int k) {
return ((_value >> k) & 1) == 1;
}
}
class E {
int longestPalindrome(String s) {
if (s.isEmpty) {
return 0;
}
BitSet bitSet = BitSet();
int ans = 0;
for (int ch in s.runes) {
int pos = 0;
if (ch >= 65 && ch <= 90) {
pos = ch - 65 + 26;
} else {
pos = ch - 97;
}
if (bitSet.get(pos)) {
ans += 2;
}
bitSet.flip(pos);
}
return min(ans + 1, s.length);
}
int min(int a, int b) {
return a < b ? a : b;
}
}