Map和Set习题

本文通过力扣138题和771题,结合牛客网的旧键盘问题,深入探讨Java中Map和Set数据结构的应用。涉及复制带有随机指针的链表、宝石与石头的匹配策略以及旧键盘输入字符的处理。
摘要由CSDN通过智能技术生成

力扣138. 复制带随机指针的链表

class Solution {
    public Node copyRandomList(Node head) {
        if(head == null) {
            return null;
        }

        Map<Node,Node> nodeMap = new HashMap<> ();
        for(Node x = head; x != null;x = x.next) {
            Node newNode = new Node(x.val);
            nodeMap.put(x,newNode);
        }
        for(Node x = head; x != null;x = x.next) {
            nodeMap.get(x).next = nodeMap.get(x.next);
            nodeMap.get(x).random = nodeMap.get(x.random);
        }
        return nodeMap.get(head);
    }
}

运行截图:
在这里插入图片描述

力扣771. 宝石与石头

class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        Set<Character> jewelSet = new HashSet<> ();
        for(int i = 0;i < jewels.length();i++) {
            jewelSet.add(jewels.charAt(i));
        }
        int ret = 0;
        for(int i = 0;i < stones.length();i++) {
            if(jewelSet.contains(stones.charAt(i))) {
                ret++;
            }
        }
        return ret;
    }
}

运行截图:
在这里插入图片描述

牛客网.旧键盘 (20)

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        String expectedStr=null;
        String actualStr=null;
        while(scanner.hasNext()) {
            expectedStr=scanner.next();
            actualStr=scanner.next();
        }
        expectedStr =expectedStr.toUpperCase();
        actualStr =actualStr.toUpperCase();
        Set<Character> actualSet=new HashSet<>();
        for (int i = 0; i < actualStr.length(); i++) {
            actualSet.add(actualStr.charAt(i));
        }
        Set<Character> ret=new HashSet<>();
        for (int i = 0; i < expectedStr.length(); i++) {
            char c=expectedStr.charAt(i);
            if (! actualSet.contains(c)){
                if (ret.add(c)){
                    System.out.print(c);
                }
            }
        }
        System.out.println();
    }
}

运行截图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值