-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path409.java
More file actions
56 lines (50 loc) · 1.65 KB
/
409.java
File metadata and controls
56 lines (50 loc) · 1.65 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
__________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public int longestPalindrome(String s) {
int[] countArray = new int[52];
for(char ch : s.toCharArray()){
if(ch >= 'a' && ch <= 'z') countArray[ch - 'a']++;
else countArray[ch-'A'+26]++;
}
int count = 0;
boolean addOne = false;
for(int i=0; i<countArray.length; i++){
if(countArray[i] % 2 == 0){
count = count + countArray[i];
}else if(countArray[i] > 1) {
count = count + (countArray[i]-1);
addOne = true;
}else if(countArray[i] == 1){
addOne = true;
}
}
if(addOne){
return ++count;
}
return count;
}
}
__________________________________________________________________________________________________
sample 34204 kb submission
class Solution {
public int longestPalindrome(String s) {
Map<Character, Integer> frequencyMap = new HashMap<>();
for(char ch:s.toCharArray()){
frequencyMap.compute(ch,(key,val)->val==null?1:val+1);
}
int totalLen = 0;
boolean oddPresent = false;
for(int i:frequencyMap.values()){
if(i%2==0)
totalLen+= i;
else{
oddPresent = true;
totalLen += i-1;
}
}
if(oddPresent) totalLen++;
return totalLen;
}
}
__________________________________________________________________________________________________