Friday, 26 May 2017

Game of Thrones - I

Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom.
But, to lock the door he needs a key that is an anagram of a certain palindrome string.
The king has a string composed of lowercase English letters. Help him figure out whether any anagram of the string can be a palindrome or not.
Input Format 
A single line which contains the input string.
Constraints 
 length of string  
Each character of the string is a lowercase English letter.
Output Format 
A single line which contains YES or NO in uppercase.
Sample Input : 01
aaabbbb
Sample Output : 01
YES
Explanation 
A palindrome permutation of the given string is bbaaabb
Sample Input : 02
cdefghmnopqrstuvw
Sample Output : 02
NO
Explanation 
You can verify that the given string has no palindrome permutation. 
Sample Input : 03
cdcdcdcdeeeef
Sample Output : 03
YES
CODE:-  main logic is if length is even then count the individual characters in ths string. Each characters duplicate count should be even, Then it ti palendrome. If the string length is odd then there should be only one character whose duplicate count is a odd number.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner myScan = new Scanner(System.in);
        String inputString = myScan.nextLine(); 
        HashMap<Character,Integer> hashMap = new HashMap<Character,Integer>();
        String ans = "NO";
       for(int i=0;i<inputString.length();i++){
           if(hashMap.containsKey(inputString.charAt(i))){
               hashMap.put(inputString.charAt(i),hashMap.get(inputString.charAt(i))+1);
           }else{
               hashMap.put(inputString.charAt(i),1);
           }
       }
        int oddCount=0;
           Set<Character> set= hashMap.keySet();
           Iterator iter = set.iterator();
           while(iter.hasNext()){
               if(hashMap.get(iter.next())%2!=0){
                   oddCount+=1;
               }
           }
        if(inputString.length()%2==0 && oddCount==0){
                ans = "YES";
        }else if(inputString.length()%2!=0 && oddCount==1){
            ans = "YES";
        }
        System.out.println(ans);
        myScan.close();
    }
}

No comments:

Post a Comment

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...