4.17 华为笔试 第一题

第一题不知道咋回事只通过20%,佬们可以帮忙看看嘛。

破案了,考试时提交的代码是直接pop然后反转,导致10翻转成01了

	StringBuilder stringBuilder = new StringBuilder();
        while(!stack.isEmpty()) {
            stringBuilder.append(stack.pop()).append(" ");
        }
	System.out.print(stringBuilder.reverse().toString().trim());

以下应该是正确的代码:

    public void solve1() {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        String[] cards = sc.nextLine().split(" ");
	  
        Deque<String> stack = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if(stack.size() >= 2 && stack.peek().equals(cards[i])) {
                String pop1 = stack.pop();
                if(stack.peek().equals(cards[i])) {
                    stack.pop();
                } else {
                    stack.push(pop1);
                    stack.push(cards[i]);
                }
            } else {
                stack.push(cards[i]);
            }
        }
        if(stack.isEmpty()) {
            System.out.print(0);
            return;
        }
	  
        StringBuilder stringBuilder = new StringBuilder();
        while(!stack.isEmpty()) {
            stringBuilder.append(stack.removeLast()).append(" ");
        }
        System.out.print(stringBuilder.toString().trim());
    }

全部评论
有10,得用String
点赞 回复 分享
发布于 2024-04-17 22:17 江苏
10无法正常输出,会被反转成01
点赞 回复 分享
发布于 2024-04-17 22:08 天津

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
3
8
分享

创作者周榜

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