Dothraki is 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 palindrome. He starts to go through his box of strings, checking to see if they can be rearranged into a palindrome. Given a string, determine if it can be rearranged into a palindrome. Return the string YES
or NO
.
Example:
Input: s="aaabbbb"
Output: YES
Approach
Java
public class GameOfThronesI {public static void main(String[] args) {String s = "aaabbbb";String result = gameOfThrones(s);System.out.println(result);}private static String gameOfThrones(String s) {int f[] = new int[26];for (int i = 0; i < s.length(); i++) {f[s.charAt(i) - 'a']++;}int cnt = 0;if (s.length() <= 1) {return "YES";}for (int i = 0; i < 26; i++) {if (f[i] % 2 == 1) {cnt++;}}if (cnt > 1) {return "NO";}if (cnt == 1 && s.length() % 2 == 0) {return "YES";}return "YES";}}
C++
#include <bits/stdc++.h>using namespace std;string gameOfThrones(string s){int f[26] = {0};for (int i = 0; i < s.size(); i++){f[s[i] - 'a']++;}int cnt = 0;if (s.size() <= 1){return "YES";}for (int i = 0; i < 26; i++){if (f[i] & 1){cnt++;}}if (cnt > 1){return "NO";}if (cnt == 1 && s.size() % 2 == 0){return "YES";}return "YES";}int main(){string s = "aaabbbb";string result = gameOfThrones(s);cout << result << "\n";return 0;}
No comments:
Post a Comment