题解 | #MP3光标位置#
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
模拟场景,没有任何技巧。没有算法
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int nums = in.nextInt();
String operate = in.next();
int cursorIndex = 0; // 数据索引的位置
int numMoveIndex = 0;
char[] chars = operate.toCharArray();
// 主要思路就是在游标移动的时候,同一时间也记录下屏幕最上方的那个数据位置
for (int i = 0; i < chars.length; i++) {
int m = operate(chars[i]);
cursorIndex += m;
if (cursorIndex < 0) {
cursorIndex = nums - 1;
} else if (cursorIndex > nums - 1) {
cursorIndex = 0;
}
// 前两个if else是判断特殊情况
if (cursorIndex == nums - 1) {
numMoveIndex = nums - 4;
} else if (cursorIndex == 0) {
numMoveIndex = 0;
} else if (cursorIndex < numMoveIndex) { // 后面2中情况,是判断走到屏幕最下方和屏幕最上方时候的处理方案
numMoveIndex--;
} else if (cursorIndex > numMoveIndex + 3) {
numMoveIndex++;
}
}
int start = cursorIndex;
cursorIndex = numMoveIndex;
int loop = Math.min(nums, 4);
for (int i = 0; i < loop; i++) {
if (cursorIndex < 0) {
cursorIndex = nums - 1;
} else if (cursorIndex > nums - 1) {
cursorIndex = 0;
}
System.out.print((cursorIndex + 1) + " ");
cursorIndex += 1;
}
System.out.println();
System.out.println(start + 1);
}
}
private static int operate(char c) {
if (c == 'U') {
return -1;
} else if (c == 'D') {
return 1;
} else {
return 0;
}
}
}