题解 | #MP3光标位置#

MP3光标位置

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

不知道为什么都是面向过程的解法

简单的OOP

用一个新类来帮忙弥补不需要翻页的情况,注意r需要缩小

注意一下 private 方法是不能被override的, 必须得变成public/protected 才可以被子类 重写

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        String input = in.nextLine();
        char[] cmds = input.toCharArray();
        solver(n, cmds);
    }
    private static void solver(int n, char[] cmds) {
        SongList item = null;
        if (n <= 4) {
            item = new SmallSongList(n);
        } else
            item = new SongList(n);
        for (int i = 0; i < cmds.length; i++) {
            item.operate(cmds[i]);
        }
        item.printWindow();
        item.printPtr();
    }
    private static class SmallSongList extends SongList{
        public SmallSongList(int n) {
            super(n);
            r = n-1;
        }
        @Override
        public void Up() {
            if (ptr > 0 )
                ptr--;
        }
        @Override
        public void Down() {
            if (ptr < size-1)
                ptr++;
        }
    }
    private static class SongList{
        protected int size;
        protected int l;
        protected int r;
        protected int ptr;
        protected int[] list;
        public void printWindow() {
            for (int i = l; i <= r; i++) {
                System.out.print(list[i]+" ");
            }
            System.out.println();
        }
        public void printPtr() {
            System.out.println(list[ptr]);
        }
        public void operate(char c) {
            if (c == 'U')
                Up();
            if (c == 'D')
                Down();
        }
        public SongList(int size) {
            this.size = size;
            list = new int[size];
            for (int i = 0; i < size; i++) {
                list[i] = i+1;
            }
            l = 0;
            r = 3;
            ptr = 0;
        }
        public void Up() {
            if (l==ptr) {
                if (l == 0) {
                    l = size-4;
                    r = size-1;
                    ptr = r;
                } else {
                    l--;
                    r--;
                    ptr--;
                }
            } else {
                ptr--;
            }
        }
        public void Down() {
            if (r==ptr) {
                if (r == size-1) {
                    l = 0;
                    r = 3;
                    ptr = l;
                } else {
                    l++;
                    r++;
                    ptr++;
                }
            } else {
                ptr++;
            }
        }
    }
}

全部评论

相关推荐

06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
06-16 15:04
黑龙江大学 Java
零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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