You are viewing a single comment's thread. Return to all comments →
JAVA 8 simple solution:
public static String isValid(String s) { Map<Character,Integer> map = new HashMap<>(); for(Character c : s.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } List<Integer> list = new ArrayList<>(map.values()); Collections.sort(list); int min =list.get(0); int max= list.get(list.size() - 1); if(min == max) { return "YES"; } int minCount = 0; int maxCount = 0; for(int val : list) { if(min == val) { minCount++; } if(max == val) { maxCount++; } } System.out.println("max:"+max+"\n min:"+min); System.out.println("maxCount:"+maxCount+"\n minCount:"+minCount); if(max - min > 1 ) { if(minCount != 1) { return "NO"; } } return ((maxCount + minCount == list.size() ) && (maxCount < 2 || minCount <2 ) ? "YES": "NO" ); }
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and the Valid String
You are viewing a single comment's thread. Return to all comments →
JAVA 8 simple solution: