In this HackerRank Game of Thrones – I problem solution we have given a string, determine if it can be rearranged into a palindrome. Return the string YES or NO.
Problem solution in Python.
def can_be_palindrome(string): string = sorted(string) current_letter_count = 1 middle = False for index, char in enumerate(list(string[1:])): if string[index] != char: if current_letter_count % 2: if not middle: middle = True else: return False current_letter_count += 1 return True print('YES' if can_be_palindrome(input()) else 'NO')
Problem solution in Java.
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(); String ans; int[]count=new int[26]; for(int i=0;i<inputString.length();i++) count[inputString.charAt(i)-'a']++; int odds=0; for(int i=0;i<26;i++) if(count[i]%2==1) odds++; if(((inputString.length()%2==0)&&odds==0)||((inputString.length()%2==1)&&odds==1)) ans="YES"; else ans="NO"; System.out.println(ans); myScan.close(); } }
Problem solution in C++.
#include <vector> #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { vector<long long> stat(26,0); string str; getline(cin,str); for(int i=0; i<str.size(); i++){ stat[str[i]-'a']++; } int odd=0; for(int i=0; i<stat.size(); i++){ if(stat[i] % 2 == 1) odd++; if(odd > 1){ cout<<"NO"; break; } } if(!(odd >1 )) cout<<"YES"; return 0; }
Problem solution in C.
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int x = 0, i, y = 0; char a[1000001], b[27]={0}; scanf ("%s", &a); x = strlen (a); for (i = 0; i < x; i++){ b[a[i]-'a']++; } for (i = 0; i < 26; i++){ if (b[i]%2 == 1) y++; } if (x % 2 == 1){ if (y == 1){ printf ("YES"); return 0; } }else{ if (y == 0){ printf ("YES"); return 0; } } printf("NO"); return 0; }