有一个判断需要注意一下:
当你的屏幕不是第一页的时候,你的mouse是最后一首歌的时候
你可能写的是 else if(first != 1 && mouse == first+3 && strA[i] == 'D') first++; mouse++
实际上是错误的, 因为你保证了不是在第一页 但是可能是在最后一页,那么
first = 7 而你的光标不是在第一首7 或者最后一首 10 处,你可能在 8 或者 9
此时first = 8,mouse = 9/10,但是我们在打印的时候从first开始往后打印四个,这个时候就越界
其实mouse = 7 或者 10在之前都处理过这个不用的担心
那么 你需要保证first != n-3 也就是不能为最后一页
实际上也不可能为第一页,因为n > 4,n最小是5 5-3 = 2,所以first 最小也就是2(只有first = 1 才是第一页)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String num = sc.nextLine();
String str = sc.nextLine();
mouseMove(num,str);
}
private static void mouseMove(String num, String str) {
int n = Integer.parseInt(num);
char[] strA = str.toCharArray();
//代表这一页的第一首
int first = 1;
//mouse 代表光标的位置
int mouse = 1;
if (n <= 4) {
for (int i = 0; i < strA.length; i++) {
if (mouse == 1 && strA[i] == 'U') {
mouse = n;
}
else if (mouse == n && strA[i] == 'D') {
mouse = 1;
}else if(strA[i] == 'U'){
mouse--;
}else if(strA[i] == 'D'){
mouse++;
}
}
for(int i = 1;i < n;i++){
System.out.print(i+" ");
}
System.out.println(n);
System.out.println(mouse);
}else{
for(int i = 0;i < strA.length;i++){
if(first == 1 && mouse == 1 && strA[i] == 'U'){
mouse = n;
first = n-3;
}else if(first == n-3 && mouse == n && strA[i] == 'D'){
first = 1;
mouse = 1;
}else if(first != 1 && mouse == first && strA[i] == 'U'){
first--;
mouse--;
}else if(first != n-3 && mouse == first+3 && strA[i] == 'D'){
first++;
mouse++;
}else if(strA[i] == 'U'){
mouse--;
}else if(strA[i] == 'D'){
mouse++;
}
}
for(int i = first;i < first+3;i++){
System.out.print(i+" ");
}
System.out.println(first+3);
System.out.println(mouse);
}
}
}