forked from adityabisoi/ds-algo-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.java
88 lines (77 loc) · 2.8 KB
/
solution.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class solution {
// Complete the happyLadybugs function below.
static String happyLadybugs(String b) {
b = b.toLowerCase();
// we'll note if string has _ then we can swap places
boolean canSwap = false;
boolean isEmpty = true;
// initialise char freq array
int[] chars = new int[26];
for (int i = 0; i < b.length(); i++) {
if (b.charAt(i) == '_') {
canSwap = true;
} else {
// note the char frequencies
chars[((int) b.charAt(i)) - 97]++;
isEmpty = false;
}
}
// if the string is empty there are no unhappy lady bugs
if (isEmpty) {
return "YES";
}
// if there is only one ladybug we can't make it happy
if (b.length() <= 1) {
return "NO";
}
// if there exists only one ladybug of any color, we can't make them happy
for (int i = 0; i < 26; i++) {
if (chars[i] == 1) {
return "NO";
}
}
// for i=0 if right ladybug is not of same color and we can't swap,return NO
for (int i = 0; i < b.length(); i++) {
if (i == 0) {
if (b.charAt(i) != b.charAt(i + 1) && !canSwap) {
return "NO";
}
// for rightmost ladybug, if ladybug is not of same color and we can't swap
// return NO
} else if (i == b.length() - 1) {
if (b.charAt(i) != b.charAt(i - 1) && !canSwap) {
return "NO";
}
// if adjacent ladybug is not of same color and we can't swap, return NO
} else {
if (b.charAt(i) != b.charAt(i - 1) && b.charAt(i) != b.charAt(i + 1) && !canSwap) {
return "NO";
}
}
}
return "YES";
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int g = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int gItr = 0; gItr < g; gItr++) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
String b = scanner.nextLine();
String result = happyLadybugs(b);
bufferedWriter.write(result);
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
}