Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save samarthsewlani/8d2bb5d61e1413e1d1e9b53a002fdecb to your computer and use it in GitHub Desktop.
Save samarthsewlani/8d2bb5d61e1413e1d1e9b53a002fdecb to your computer and use it in GitHub Desktop.
Longest Palindrome by Concatenating Two Letter Words
//https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/
class Solution {
public int longestPalindrome(String[] words) {
int n = words.length, count = 0;
Map<String, Integer> visited = new HashMap<>();
for(int i=0;i<n;i++){
String word = words[i];
String reverseWord = word.charAt(1) + "" + word.charAt(0) ;
if(visited.containsKey(reverseWord) && visited.get(reverseWord)>0){
count += 4;
visited.put(reverseWord, visited.get(reverseWord) - 1);
}
else{
visited.put(word, visited.getOrDefault(word, 0) + 1);
}
}
for(String remainingWord:visited.keySet()){
if((remainingWord.charAt(0) == remainingWord.charAt(1)) && visited.get(remainingWord)>0){
count += 2;
break;
}
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment