-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSherlockandtheValidString.java
More file actions
60 lines (54 loc) · 1.73 KB
/
Copy pathSherlockandtheValidString.java
File metadata and controls
60 lines (54 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static String isValid(String s){
HashMap<Character, Integer> counts = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (counts.containsKey(c)) {
counts.put(c, counts.get(c) + 1);
} else {
counts.put(c, 1);
}
}
HashMap<Integer, Integer> appearCount = new HashMap<Integer, Integer>();
for (Integer count : counts.values()) {
if (appearCount.containsKey(count)) {
appearCount.put(count, appearCount.get(count) + 1);
} else {
appearCount.put(count, 1);
}
}
if (appearCount.size() == 1) {
return "YES";
} else if (appearCount.size() > 2) {
return "NO";
} else {
int appearOne = -1;
int appearMoreThanOne = -1;
for (int count: appearCount.keySet()) {
if (appearCount.get(count) == 1) {
appearOne = count;
} else {
appearMoreThanOne = count;
}
}
if (appearOne == 1 && appearCount.get(1) == 1) {
return "YES";
}
if (appearOne - 1 == appearMoreThanOne) {
return "YES";
}
return "NO";
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
String result = isValid(s);
System.out.println(result);
}
}