小明正在规划一个大型数据中心机房,为了使得机柜上的机器都能正常满负荷工作,需要确保在每个机柜边上至少要有一个电箱。
为了简化题目,假设这个机房是一整排, 表示机柜, 表示间隔,请你返回这整排机柜,至少需要多少个电箱。 如果无解请返回 。
cabinets = "MIIM"
其中 表示机柜, 表示间隔
2
表示至少需要2
个电箱
1<= strlen(cabinets) <= 10000
其中 cabinets[i]
= ‘M’
或者 'I'
MIIM
2
MIM
1
M
-1
MMM
-1
I
0
import java.util.LinkedList;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
*
* @Author: Amos
* @E-mail: amos@amoscloud.com
* @Date: 2023/2/16
* @Time: 4:49
* @Description:
*/
public class Main0213 {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String line = scanner.next();
System.out.println(solution(line));
}
}
public static int solution(String line) {
int n = line.length();
LinkedList<Integer[]> stack = new LinkedList<>();
boolean stick = false;
for (int i = 0; i < n; i++) {
if (line.charAt(i) == 'M') {
boolean left = i - 1 < 0 || line.charAt(i - 1) == 'M';
boolean right = i + 1 >= n || line.charAt(i + 1) == 'M';
if (left && right) return -1;
Integer[] range = {Math.max(0, i - 1), Math.min(n - 1, i + 1)};
if (stack.size() > 0 && !stick) {
int e1 = stack.getLast()[1];
int s2 = range[0];
if (e1 == s2) {
stack.removeLast();
stick = true;
}
} else {
stick = false;
}
stack.addLast(range);
}
}
return stack.size();
}
}