Valid String

 A string to be valid if all characters of the string appear the same number of times

Input : aabbcc

Output: valid

Code

package wordpress;

import java.util.LinkedHashMap;
import java.util.Locale;

public class ValidString {

    public static String validateTheInputString(String input) {
        input = input.toLowerCase(Locale.ROOT);
        LinkedHashMap<Character, Integer> hashMap = new LinkedHashMap<>();
        for (Character c : input.toCharArray()) {
            if (hashMap.containsKey(c)) {
                int count = hashMap.get(c);
                hashMap.put(c, ++count);
            } else {
                hashMap.put(c, 1);
            }
        }
        Integer initialValue = hashMap.get(input.toCharArray()[0]);
        for (Integer value : hashMap.values()) {
            if (value != initialValue) {
                return "Invalid";
            }
        }
        return "valid";
    }

    public static void main(String[] args) {
        System.out.println(validateTheInputString("aabbcc")); // valid
        System.out.println(validateTheInputString("abcd")); // valid
        System.out.println(validateTheInputString("a")); // valid
        System.out.println(validateTheInputString("aab")); // invalid
        System.out.println(validateTheInputString("aA")); // valid
    }
}
Scroll to Top