Determine whether any permutation of a string is a palindrome.

For a string to be a palindrome, it should either have all distinct characters in even numbers ( so as to form pairs ) or it could have all characters in even numbers except for a single character which cannot be paired. If the string contains more than one character that cannot be paired then the string is not a palindrome.

Consider the following examples,

input_string=”carrace”

A possible palindromic permutation of the input string could be – “racecar”.

input_string=”daily”

None of the possible permutations of the input string could be palindromic.

My solution uses a HashMap to count the instances of all characters in the string and then check if all characters can be paired.

public boolean isSubstringPalindrome(String s)
	{
		//check if every character appears twice and if not only one character appears once
		HashMap<Character,Integer> map=new HashMap<Character,Integer>();

		for(char ch: s.toCharArray())
			map.put(ch,map.getOrDefault(ch,0)+1);

		boolean check=false;
		for(int x: map.values())
		{
			if(x%2==1 &&  check)
				return false;

			if(x%2==1)
				check=true;
		}

		return true;
	}

Leave a comment