The Valid String
Input: aabbcd
Output: NO
Explanation:we would need to remove two characters, both 'c' and 'd' —>'aabb' or 'a' and 'b' —> 'abcd', to make it valid. We are limited to removing only one character so it is "NO".public class Solution {
/**
* @param s: a string
* @return: if valid return "YES" else return "NO"
*/
public String isValid(String s) {
// write your code here
if (s == null || s.length() <= 3) return "YES";
int[] hash = new int[26];
for (char c : s.toCharArray()) hash[c - 'a']++;
int first = 0, second = 0;
int sum_first = 0, sum_second = 0;
for (int i = 0; i < 26; i++) {
if (hash[i] == 0) continue;
if (first == 0) {
first = hash[i];
sum_first = 1;
} else if (hash[i] == first) {
sum_first++;
} else if (second == 0) {
second = hash[i];
sum_second = 1;
} else if (hash[i] == second) {
sum_second++;
} else
return "NO";
}
if (second == 0) return "YES";
if ((first == 1 || first == second + 1) && sum_first == 1) return "YES";
if ((second == 1 || second == first + 1) && sum_second == 1) return "YES";
return "NO";
}
}Last updated