(七) 集合

集合

集合是一个不能存放重复元素的容器

Set接口

public interface Set<E> {
    void add(E e);

    void remove(E e);

    boolean contain(E e);

    int getSize();

    boolean isEmpty();
}

使用二分搜索树实现集合

public class BSTSet<E extends Comparable<E>> implements Set<E> {

    private BST<E> bst = new BST<>();

    public BSTSet() {
        this.bst = new BST<>();
    }

    @Override
    public void add(E e) {
        bst.add(e);
    }

    @Override
    public void remove(E e) {
        bst.remove(e);
    }

    @Override
    public boolean contain(E e) {
        return bst.contains(e);
    }

    @Override
    public int getSize() {
        return bst.getSize();
    }

    @Override
    public boolean isEmpty() {
        return bst.isEmpty();
    }
}

使用链表实现集合

public class LinkedListSet<E> implements Set<E>{

    private LinkedList<E> linkedList;

    public LinkedListSet(){
        linkedList = new LinkedList<>();
    }

    @Override
    public void add(E e) {
        if (!linkedList.contain(e)) {
            linkedList.addFirst(e);
        }
    }

    @Override
    public void remove(E e) {
        linkedList.removeElement(e);
    }

    @Override
    public boolean contain(E e) {
        return linkedList.contain(e);
    }

    @Override
    public int getSize() {
        return linkedList.getSize();
    }

    @Override
    public boolean isEmpty() {
        return linkedList.isEmpty();
    }
}

解决一个问题

LeetCode中的804号问题, 不同的福尔斯密码

import java.util.Set;
import java.util.TreeSet;

class Solution {
    // 不同的福尔斯密码  leetcode中第804号问题
    public int uniqueMorseRepresentations(String[] words) {
        Set<String> set = new TreeSet<String>();
        String[] code = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
                "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
        for (String word : words) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < word.length(); i++) {
                sb.append(code[word.charAt(i) - 'a']);
            }
            System.out.println("sb.toString = " + sb.toString());
            set.add(sb.toString());
        }

        return set.size();
    }

    public static void main(String[] args) {
        int count = new Solution().uniqueMorseRepresentations(new String[]{"gin", "zen", "gig", "msg"});
        System.out.println("count = " + count);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值