题目描述:
输入一个长度为4的倍数的字符串,字符串中仅包含WASD四个字母。
将这个字符串中的连续子串用同等长度的仅包含WASD的字符串替换,如果替换后整个字符串中WASD四个字母出现的频数相同,那么我们称替换后的字符串是“完美走位”。
求子串的最小长度。
如果输入字符串已经平衡则输出0。
输入
一行字符表示给定的字符串s
数据范围:
1<=n<=10^5且n是4的倍数,字符串中仅包含WASD四个字母。
输出
一个整数表示答案
示例1:
输入:
WASDAASD
输出:
1
说明:
将第二个A替换为W,即可得到完美走位 。
示例2:
输入:
AAAA
输出:
3
说明:
将其中三个连续的A替换为WSD,即可得到完美走位
个人解法
不保证通过率
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
/**
*
*/
public class 完美走位 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
char[] items = input.toCharArray();
Arrays.sort(items);
String s = new String(items);
char[] c = new char[]{'A', 'D', 'S', 'W'};
int numA = !s.contains("A") ? 0 : s.lastIndexOf("A") + 1;
int numD = !s.contains("D") ? 0 : s.lastIndexOf("D") + 1 - numA;
int numS = !s.contains("S") ? 0 : s.lastIndexOf("S") + 1 - numD - numA;
int numW = s.length() - numA - numD - numS;
int[] nums = new int[]{numA, numD, numS, numW};
int head = 0, tail = 0;
int mid = (numA + numD + numS + numW) / 4;
HashMap<Character, Integer> need = new HashMap<>();
HashMap<Character, Integer> tmp = new HashMap<>();
for (int i = 0; i < 4; i++) {
need.put(c[i], nums[i] > mid ? nums[i] - mid : 0);
tmp.put(c[i], 0);
}
items = input.toCharArray();
int min = items.length;
while (head < items.length) {
if (tmp.get('A') >= need.get('A') &&
tmp.get('D') >= need.get('D') &&
tmp.get('S') >= need.get('S') &&
tmp.get('W') >= need.get('W')) {
tmp.put(items[head], tmp.get(items[head]) - 1);
if (tail - head < min) {
min = tail - head;
}
head++;
} else {
if (tail == items.length - 1) {
break;
}
tmp.put(items[tail], tmp.get(items[tail]) + 1);
tail++;
}
}
System.out.println(min);
}
}