-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestPalindrome.java
More file actions
32 lines (28 loc) · 1010 Bytes
/
longestPalindrome.java
File metadata and controls
32 lines (28 loc) · 1010 Bytes
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
import java.util.HashSet;
// Time Complexity : O(n)
class Solution {
public int longestPalindrome(String s) {
int length = 0;
// Create a HashSet...
HashSet<Character> set = new HashSet<>();
// Traverse every element through loop....
for(int i=0;i<s.length();i++){
// convert string to char
char ch = s.charAt(i);
// If set contains character already, remove that character & adding 2 to length...
// It means we get pair of character which is used in palindrome...
if(set.contains(ch)){
length += 2;
set.remove(ch);
}else{
// Otherwise, add the character to the hashset...
set.add(ch);
}
}
// If the size of the set is greater than zero, move length forward...
if(set.size()>0){
length++;
}
return length; // Return the length of the longest palindrome...
}
}