题解 | #MP3光标位置#
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
看题解写得都花里胡哨的,实际上只需要维护两个变量,cur指向当前选择,top指向当前列表顶部,两者关系cur - top < 4,只需要在up和down的时候注意下两者关系就行了
import java.io.IOException; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); char[] commands = scanner.nextLine().toCharArray(); int top = 1; int cur = 1; for (char command : commands) { switch (command) { case 'U': if (cur == 1) { cur = n; if (cur > 4) { top = cur - 3; } else { top = 1; } } else { cur--; if (top > cur) { top = cur; } } break; case 'D': if (cur == n) { top = cur = 1; } else { cur++; if (cur > top + 3) { top++; } } break; } } int max = Math.min(top + 3, n); for (int i = top; i <= max; i++) { System.out.print(i); if (i != max) { System.out.print(" "); } } System.out.println(); System.out.println(cur); } }