Problem 2 First Non-Repeating Characters
Last updated
Last updated
// Some code
public class Solution{
static class Node {
Node prev;
Node next;
Character ch;
Node(Character ch) {
this.ch;
}
}
private Node head;
private Node tail;
private Set<Character> repeated;
private Map<Character, Node> singled;
public Solution() {
head = new Node(null);
head.prev = head.next = head;
tail = head;
repeated = new HashSet<>();
singled = new HashMap<>();
}
public void read(char ch){
// if the character already exists more than once ==> ignore
if (repeated.contains(ch)) {
return;
}
Node node = singled.get(ch);
// if the character appears for the first time ==> add to the list and the nonrepeated
if (node == null) {
node = new Node(ch);
append(Node);
}
// if the character is already in the nonrepeated ==> remove it from the map and list
// put it into the repeat set
else {
remove(Node);
}
}
private void append(Node node){
// append to map
// append to the DLL
singled.put(node.ch, node);
tail.next = node;
node.prev = tail
node.next = head;
tail = tail.next;
}
private void remove(Node node) {
// remove from the map
// add to repeat set
// remove from DLL
node.prev.next = node.next;
node.next.prev = node.prev;
if (node == tail) {
tail = node.prev;
}
node.prev = node.next = null;
singled.remove(node.ch);
repreated.add(node.ch);
}
private Character firstNonRepeating() {
if (head == tail) {
return null;
}
return head.next.ch;
}
}// Some code
public class Solution{
static class Node {
Node prev;
Node next;
Character ch;
}
Node(Character ch) {
this.ch = ch;
}
private Node head;
private Node tail;
private Map<Character, Node> map;
public Solution{
head = new Node(null);
head.prev = head.next = head;
tail = head;
map = new HashMap<>();
}
public void read(char ch) {
// case 1
if (!map.containsKey(ch)) {
Node node = new Node(ch);
append(Node);
}
// case 2.2
else if (map.get(ch) != null) {
remove(map.get(ch));
}
// case 2.1, 2nd timt to see ==> do nothing
}
private void append(Node node) {
map.put(node.ch, node);
tail.next = node;
node.prev = tail;
node.next = head;
tail = tail.next;
}
private void remove(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
if (node == tail) {
tail = node.prev;
}
node.prev = node.next = null;
map.put(node.ch, null);
}
public Character firstNonRepeating() {
if (head == tail) {
return null;
}
return head.next.ch;
}
}