Sherlock and the Valid String solution

Published on August 05, 2021
Last updated August 05, 2021

Given problem statment

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
1 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.

solution in java

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        boolean isValid = true;

        int[] count = new int[26];

        for (int i = 0; i < str.length(); i++) {
            count[str.charAt(i) - 'a']++;
        }
        int available_deductions = 1;
        for (int i = 0; i < 26; i++) {
            if (count[i] != count[str.charAt(0) - 'a'] && count[i] != 0) {
                if (available_deductions > 0) {
                    count[i]--;
                    available_deductions--;
                    continue;
                }
                isValid = false;
                break;
            }
        }
        String result = isValid ? "YES" : "NO";
        System.out.println(result);
        sc.close();
    }
}


Tags :