一次遍历,很简单的解法

字面意思,MP3屏幕同时显示4首歌的列表,按上/下键,光标上/下移1次

故此题需要解决2个问题
1.每次发生按键操作,更新光标位置
2.记录可能发生的列表变动

光标位置随操作变动,变量记录即可;
显示列表,由于屏幕只显示4首歌,因此只需要记录当前列表的顶部(top)或底部(bottom)位置,
即可得到列表为top top+1 top+2 top+3   或  bottom-3 bottom-2 bottom-1 bottom
代码如下
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int top = 1, pos = 1;//初始状态:列表顶部为1 光标位置为1
        char c[] = sc.next().toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 'D') {
                if (pos + 1 > n)//光标下移到最后一首歌
                    top = pos = 1;//再往下则回到初始状态
                else
                    pos++;//光标正常下移
                top += pos - top == 4 ? 1 : 0;//顶部与光标距离即将为4则顶部被其下一首歌顶替
            }

            if (c[i] == 'U') {
                if (pos - 1 < 1) {//光标上移到第一首歌
                    pos = n;//再往上则为最后一首
                    top = n - 3;//此时顶部为歌曲总数-3
                } else pos--;//光标正常上移
                top -= pos - top < 0 ? 1 : 0;//光标位置即将比顶部还靠上时,顶部变为其上一首歌
            }
        }

        if (n > 4)//超过4首歌,列表为top~top+3
            System.out.printf("%d %d %d %d\n", top, top + 1, top + 2, top + 3);
        else {//4首歌以内,列表可能为1 12 123 1234 其中之一
            System.out.print(1);
            for (int i = 2; i <= n; i++)
                System.out.print(" " + i);
            System.out.println();
        }
        System.out.println(pos);

    }
}