LeetCode problem#409
Longest Palindrome
Solved in 1 languageJava
Solution
23 lines
1import java.util.HashSet;
2
3class Solution {
4 public int longestPalindrome(String s) {
5 HashSet<Character> seenCharacters = new HashSet<Character>();
6 int count = 0;
7
8 for (int i = 0; i < s.length(); i++)
9 {
10 if (seenCharacters.contains(s.charAt(i)))
11 {
12 count += 2;
13 seenCharacters.remove(s.charAt(i));
14 }
15 else
16 {
17 seenCharacters.add(s.charAt(i));
18 }
19 }
20
21 return count < s.length() ? count + 1 : count;
22 }
23}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.