It is almost time to complete the first 2-hour block of the day. I work using a technique called Deep Work. Today I got up at 05:00 AM and have been at it for about two hours. I believe I have enough time to complete this post.
I received an email message from HackerRank with the Game of Thrones – 1 challenge. The challenge is simple. We have to determine if a string of characters may be converted to a palindrome or not. Keep in mind that palindromes longer than one character are made up of pairs of characters.
With that in mind, here is my solution which was accepted:
// Complete the gameOfThrones function below. static String gameOfThrones(String s) { // **** get the length of the string **** int len = s.length(); // **** check for single character strings **** if (len == 1) return "YES"; HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); // **** traverse the string counting characters **** for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (hm.containsKey(ch)) { int count = hm.get(ch); count++; hm.put(ch, count); } else { hm.put(ch, 1); } } // **** iterate through the string counting odd counts **** int oddCount = 0; for (Map.Entry<Character, Integer> entry : hm.entrySet()) { int charCount = entry.getValue(); if ((charCount % 2) == 1) oddCount++; } // **** **** if (oddCount <= 1) return "YES"; else return "NO"; }
The following list contains the tests I ran before submitting the code:
aaabbbb YES cdefghmnopqrstuvw NO aabbccdd YES cdcdcdcdeeeef YES xaa YES axbyaabb NO
You can find my complete solution in my GitHub repository.
If you have comments or questions regarding this or any other post in this blog, do not hesitate and leave me a note bellow.
Keep on learning, practicing and having fun developing software;
John
Follow me on Twitter: @john_canessa