JAVA | 3 Approaches | Everything you'd need ✅
Please Upvote :D\n---\n##### 1. Using HashSet:\njava []\nclass Solution {\n    public int longestPalindrome(String s) {\n        Set<Character> set = new HashSe
# Please Upvote :D\n---\n##### 1. Using HashSet:\n``` java []\nclass Solution {\n    public int longestPalindrome(String s) {\n        Set<Character> set = new HashSet<>();\n        int len = 0;\n        for (char c : s.toCharArray()) {\n            if (set.contains(c)) {\n                len += 2;\n                set.remove(c);\n            }\n            else set.add(c);\n        }\n\n        return set.size() > 0 ? len + 1 : len;\n    }\n}\n\n// TC: O(n), SC: O(n)\n```\n---\n##### 2. Using HashMap:\n``` java []\nclass Solution {\n    public int longestPalindrome(String s) {\n        Map<Character, Integer> map = new HashMap<>();\n        for (char c : s.toCharArray()) {\n            map.put(c, map.getOrDefault(c, 0) + 1);\n        }\n\n        int len = 0;\n        for (int i : map.values()) {\n            len += (i % 2 == 0)? i : i - 1;\n        }\n\n        return len < s.length() ? len + 1 : len;\n    }\n}\n\n// TC: O(n), SC: O(n)\n```\n---\n##### 3. Using Frequency array:\n``` java []\nclass Solution {\n    public int longestPalindrome(String s) {\n        int[] charCount = new int[128];\n        for (char c : s.toCharArray()) {\n            charCount[c]++;\n        }\n\n        int len = 0;\n        for (int count : charCount) {\n            len += 2 * (count / 2);\n        }\n\n        return len < s.length() ? len + 1 : len;\n    }\n}\n\n// TC: O(n), SC: O(1)\n```
['Array', 'Hash Table', 'Java']