题解 | #MP3光标位置#

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.hasNextLine()) { 
            int total = Integer.parseInt(in.nextLine());
            String command = in.nextLine();
            int[] res = process(total, command);
            for(int i = 1; i < res.length; i++) {
                System.out.print(res[i] + " ");
            }
             System.out.println();
             System.out.println(res[0]);
        }
    }

    public static int[] process(int total, String command) {
        int cur = 1, limit = total >= 4 ? 4 : total;
        int from = 1, to = total >= 4 ? 4 : total;
        char[] c = command.toCharArray();
        for(int i = 0; i < command.length(); i++) {
            if(c[i] == 'D') {
                if(cur+1 > to) {
                    if(to < total) {
                        to = to+1;
                        from = from+1;
                        cur = cur+1;
                    } else {
                        to = limit;
                        from = 1;
                        cur = 1;
                    }
                } else {
                    cur = cur+1;
                }
            } else {
                if(cur-1 < from) {
                    if(from == 1) {
                        from = total-limit+1;
                        to = total;
                        cur = to;
                    } else {
                        from = from -1;
                        to = to-1;
                        cur = cur-1;
                    }
                } else {
                    cur = cur-1;
                }
            }
        }
        int[] res = new int[to-from+2];
        res[0] = cur;
        for(int i = from; i <= to; i++) res[i-from+1] = i;
        return res;
    }
}

全部评论

相关推荐

ming_ri:“很抱歉,您的简历和我们当前的职位需求不是很匹配”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务