Thursday, July 27, 2017

Whether String is Palindrome or not

package com.array;

import java.util.HashMap;
import java.util.Map;

/* To find whether String is a Palindrome or not
 * Convert String to Map with char as key and count as value
 * Calculate if count is even or count is odd only once */

public class StringPalindrome {

     public static void main(String[] args) {
           String arrayStr[] = { "NitiN", "Paras", "tactactoto" };
           for(String str:arrayStr){
                System.out.println("String is "+ str);
                Map map = countEveryCharInMap(str);
                System.out.println("String conversion into Map " + map);
                palindrome(map);
           }
     }

     static Map<Character, Integer> countEveryCharInMap(String str) {
           Map<Character, Integer> map = new HashMap<>();
           for (int i = 0; i < str.toCharArray().length; i++) {
                char key = str.charAt(i);
                int count = 1;
                if (map.containsKey(key)) {
                     Integer value = map.get(key);
                     Integer newValue = ++value;
                     map.put(key, newValue);
                } else
                     map.put(key, count);
           }
           return map;
     }

     static void palindrome(Map<Character, Integer> map) {
           int oddCountflag = 0;
           for (Character c : map.keySet()) {
                if (map.get(c) % 2 != 0)
                     oddCountflag++;
           }
           if (oddCountflag <= 1)
                System.out.println("PALINDROME");
           else
                System.out.println("NOT A PALINDROME");
     }
}

Output:

String is NitiN
String conversion into Map {t=1, i=2, N=2}
PALINDROME

String is Paras
String conversion into Map {P=1, a=2, r=1, s=1}
NOT A PALINDROME

String is tactactoto
String conversion into Map {a=2, c=2, t=4, o=2}
PALINDROME

No comments:

Post a Comment