-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
86 lines (78 loc) · 2.29 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
// https://leetcode.com/problems/replace-the-substring-for-balanced-string
class Solution {
public int balancedString(String s) {
int n = s.length();
int freq[] = new int[4];
for(int i=0;i<n;i++){
char ch = s.charAt(i);
if(ch == 'Q'){
freq[0] ++;
}else if(ch == 'W'){
freq[1] ++;
}else if(ch == 'E'){
freq[2] ++;
}else{
freq[3] ++;
}
}
boolean flag = true;
for(int i=0;i<4;i++){
if(freq[i] != n/4)
flag = false;
}
if(flag)
return 0;
int extra[] = new int[4];
for(int i=0;i<4;i++){
extra[i] = freq[i] - n/4;
}
int j = 0;
int len = n;
for(int i=0;i<n;i++){
char ch = s.charAt(i);
if(ch == 'Q'){
extra[0] --;
}else if(ch == 'W'){
extra[1] --;
}else if(ch == 'E'){
extra[2] --;
}else{
extra[3] --;
}
if(check(extra)){
len = Math.min(len, i-j+1);
while(j <= i){
ch = s.charAt(j);
if(ch == 'Q'){
extra[0] ++;
}else if(ch == 'W'){
extra[1] ++;
}else if(ch == 'E'){
extra[2] ++;
}else{
extra[3] ++;
}
// System.out.println(i + " " + j);
j++;
if(check(extra)){
len = Math.min(len, i-j+1);
}else{
// for(int v: extra){
// System.out.print(v + " ");
// }
// System.out.println();
break;
}
}
}
}
return len;
}
public boolean check(int arr[]){
for(int i=0;i<arr.length;i++){
if(arr[i] > 0)
return false;
}
return true;
}
}