集合
集合是一个不能存放重复元素的容器
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);
}
}

1318

被折叠的 条评论
为什么被折叠?



