题解 | #MP3光标位置#
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String a, b;
try {
a = r.readLine();
b = r.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
char[] chs = a.toCharArray();//歌曲数量1<=n<=150
char[] operate = b.toCharArray();//命令长度1<=s<=100
int i = 0, l1 = chs.length, l2 = operate.length, n = 0, current = 0, j = 0,
capacity = 4;
while (i < l1) {//得到歌曲的总数量
if (chs[i] == ' ') break;
n *= 10;
n += chs[i] - '0';
i++;
}
int[] songs = new int[n];
i = 0;
while (i < n) {//初始化歌曲数组,数组值表示歌曲的编号
songs[i] = i + 1;
i++;
}
a = "";
if (n < capacity + 1) {//歌曲数量小于4
for (i = 0; i < n; i++) {
a = a + songs[i] + " ";
}
i = 0;
while (i < l2) {//经过操作后,获得当前选中的歌曲索引
current += (operate[i] == 'U' ? -1 :
1);//将向上走转换为索引-1,向下走转换为索引+1
if (current < 0) current += n;//当选中索引为-1时,跳到最后一个
else if (current > n - 1) current -=
n;//当选中索引为n时,跳到第一个,0~n-1为数组的有效索引
i++;
}
} else {
for (i = 0; i < l2; i++) {
current += (operate[i] == 'U' ? -1 : 1);
if (current <
0) {//当选中索引为-1时,页面跳到索引为n-4,n-3,n-2,n-1,因为j为页面首索引,所以j为n-4
j = n - 4;
current += n;
}
if (current > n -
1) {//当选中索引为n时,页面跳到索引为0,1,2,4,因为j为页面首索引,所以j为0
current -= n;
j = 0;
}
if (current > j + 3) j = current -
3;//当选中索引比当前页面尾索引大时,首索引j为当前选中索引-3
if (current < j) j =
current;//当选中索引比当前页面首索引小时,首索引j为当前选中索引
}
i = j;
while (i < j + 4) {
a = a + songs[i] + " ";
i++;
}
}
a = a + "\n" + songs[current];
System.out.print(a);
}
}
腾讯公司氛围 3634人发布