题目描述:
小明正在规划一个大型数据中心机房,为了使得机柜上的机器都能正常满负荷工作,需要确保在每个机柜边上至少要有一个电箱。
为了简化题目,假设这个机房是一整排,M表示机柜,I表示间隔,请你返回这整排机柜,至少需要多少个电箱。 如果无解请返回 -1 。
输入描述:
cabinets = "MIIM"
其中M表示机柜,I表示间隔
输出描述:
2
表示至少需要2个电箱
补充说明:
1<= strlen(cabinets) <= 10000
其中 cabinets[i] = ‘M’ 或者 'I'
收起
示例1
输入:
MIIM
输出:
2
说明:
示例2
输入:
MIM
输出:
1
说明:
示例3
输入:
M
输出:
-1
说明:
示例4
输入:
MMM
输出:
-1
说明:
示例5
输入:
I
输出:
0
public class 机房布局 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
int res = 0;
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c == 'M') {
if (i + 1 < string.length() && string.charAt(i + 1) == 'I') {
res++;
i += 2;
} else if (i - 1 >= 0 && string.charAt(i - 1) == 'I') {
res++;
} else {
res = -1;
break;
}
}
}
System.out.println(res);
}
}