Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just the character at 1 index in the string, and the remaining characters will occur the same number of times. Given a string s, determine if it is valid. If so, return YES
, otherwise, return NO
.
Example:
Input: s = "abcdefghhgfedecba"
Output: YES
Approach
Java
import java.util.HashMap;public class ValidString {public static void main(String[] args) {String s = "abcdefghhgfedecba";System.out.println(isValid(s));}static String isValid(String s) {HashMap<Character, Integer> mp =new HashMap<Character, Integer>();HashMap<Integer, Integer> freq =new HashMap<Integer, Integer>();// count the frequency of each charactersfor (int i = 0; i < s.length(); i++)mp.put(s.charAt(i), mp.getOrDefault(s.charAt(i),0) + 1);for (HashMap.Entry<Character, Integer> entry :mp.entrySet())freq.put(entry.getValue(),freq.getOrDefault(entry.getValue(), 0) + 1);int bal = 0, maxf = 0;for (HashMap.Entry<Integer, Integer> entry :freq.entrySet()) {if (entry.getValue() > maxf) {maxf = entry.getValue();bal = entry.getKey();}}int count = 0, del = 0;for (HashMap.Entry<Character, Integer> entry :mp.entrySet()) {if (entry.getValue() == 1 ||entry.getValue() == bal - 1 ||entry.getValue() == bal + 1) {del++;} else if (Math.abs(entry.getValue() - bal) > 0)count++;}if (del <= 1 && count == 0)return "YES";elsereturn "NO";}}
C++
#include <bits/stdc++.h>using namespace std;string isValid(string s){map<char, int> mp;map<int, int> freq;//count the frequency of each charactersfor (char c : s)mp[c]++;for (auto it = mp.begin(); it != mp.end(); it++)freq[it->second]++;int bal = 0, maxf = 0;for (auto it = freq.begin(); it != freq.end(); ++it){if (it->second > maxf){maxf = it->second;bal = it->first;}}int count = 0, del = 0;for (auto it = mp.begin(); it != mp.end(); it++){if (it->second == 1 || it->second == bal - 1 ||it->second == bal + 1)del++;else if (abs(it->second - bal) > 0)count++;}if (del <= 1 && count == 0)return "YES";elsereturn "NO";}int main(){string s = "abcdefghhgfedecba";cout << isValid(s) << "\n";return 0;}
No comments:
Post a Comment