题解 | #MP3光标位置#

MP3光标位置

https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15

思路很简单:用一个变量 index 记录当前的页面的首个歌曲,用一个变量 cur 记录当前选中的歌曲。

分别根据不同的指令处理特殊分页,一般分页以及正常移动 cur 的情况即可,但其中输入用例的 n < =4 时,需要考虑的细节还挺多的。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) { 
            int n = in.nextInt();  //歌曲数量
            String str = in.next();  //命令
            int index = 1;  //记录列表的起始位置
            int cur = 1;  //记录当前选中的歌曲
            for(int i=0;i<str.length();i++){
                char c = str.charAt(i);
                //如果当前的指令为 U
                if(c == 'U'){
                    //特殊翻页
                    if(index == 1 && cur == 1){
                        index = n-3 > 1 ? n-3 : 1;
                        cur = n;
                    }else if(index!=1 && cur==index){  //一般翻页
                        index--;
                        cur--;
                    }else{  
                        cur = cur-1 > 0 ? cur-1 : cur;
                    }
                }else{  //指令为 D
                    //特殊翻页,这里的条件需要好好想一想:(index==1 && cur == n && n<=4)处理的是 n 小于等于4的情况
                    if((index == n-3 && cur==n||(index==1 && cur == n && n<=4))){
                        index = 1;
                        cur = 1;
                    }else if(cur == index+3){  //一般翻页
                        index++;
                        cur++;
                    }else{
                       cur++;
                    }
                }
            }
            for(int i=index;i<=n && i<index+4;i++){
                System.out.print(i+" ");
            }
            System.out.println();
            System.out.println(cur);
        }
    }
}
全部评论

相关推荐

04-12 13:42
江南大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务