题解 | #MP3光标位置#
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numsOfSongs = scan.nextInt();
int[] arr = new int[numsOfSongs];
for (int i = 0; i < numsOfSongs; i++) {
arr[i] = i + 1;
}
String order = scan.next();
char[] Order = order.toCharArray();
int cur = 0;//表示当前所在位置的数组下标
if (numsOfSongs <= 4) {
for (int i = 0; i < Order.length; i++) {
if (Order[i] == 'D') {
if (cur == numsOfSongs - 1) {
cur = 0;
} else {
cur++;
}
} else {
if (cur == 0) {
cur = numsOfSongs - 1;
} else {
cur--;
}
}
}
for (int i = 0; i < numsOfSongs; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
} else {
int top = 0;//表示开始的时候屏幕顶部的位置的下标
int bottom = 3;//表示开始的时候屏幕底部的位置的下标
//由top和bottom维护一个窗口,大小始终是4
for (int i = 0; i < Order.length; i++) {
if (Order[i] == 'D') {
if (cur < bottom) {
cur++;
} else {
//此时就是cur == bottom
//cur并不会大于bottom,因为这个创就是我们自己维护边界的,cur只能在窗口内部活动
if (bottom < numsOfSongs - 1) {
bottom++;
cur++;
top++;
} else {
//此时就是bottom == numsOfSongs - 1,即来到了底部
cur = 0;
top = 0;
bottom = 3;
}
}
} else { //指令不是'D'就是'U'
if (cur > top) {
cur--;
} else { //此时就是cur == top
if (top > 0) {
top--;
bottom--;
cur--;
} else { //否则就是top == 0了
top = numsOfSongs - 1 - 3;
bottom = numsOfSongs - 1;
cur = bottom;
}
}
}
}
for (int i = top; i <= bottom; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
System.out.println(cur + 1);
}
}

查看13道真题和解析