Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions String/Aho Corasick/AhoCorasick.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package strings;

import java.util.Arrays;

public class AhoCorasick {

static final int k = 26;

static class Node
{
int p, c, link = -1;
boolean leaf;

Node(int a, int b) { p = a; c = b; }

int[] next = new int[26], go = new int[26];
{
Arrays.fill(next, -1);
Arrays.fill(go, -1);
}
}

Node[] nodes;
int nodeCount;

AhoCorasick(int maxNodes)
{
nodes = new Node[maxNodes];
nodes[nodeCount++] = new Node(0, -1);
}

void addString(char[] s)
{
int cur = 0;
for(char ch: s)
{
int c = ch - 'a';
if(nodes[cur].next[c] == -1)
{
nodes[nodeCount] = new Node(cur, c);
nodes[cur].next[c] = nodeCount++;
}
cur = nodes[cur].next[c];
}
nodes[cur].leaf = true;
}

int link(int vIdx)
{
Node v = nodes[vIdx];
if(v.link == -1)
v.link = v.p == 0 ? 0 : go(link(v.p), v.c);
return v.link;
}

int go(int vIdx, int c)
{
Node v = nodes[vIdx];
if(v.go[c] == -1)
v.go[c] = v.next[c] != -1 ? v.next[c] : vIdx == 0 ? 0 : go(link(vIdx), c);
return v.go[c];
}
}
36 changes: 36 additions & 0 deletions String/Suffix Trie/SuffixTrie.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package strings;

public class SuffixTrie {

static final int R = 26; //Alphabet (lowercase etters in below implementation)

static class Node { Node[] next = new Node[R]; int val = -1; }

Node root = new Node();

void put(char[] s, int idx) // O(n) where n = |s|. Can be implemented recursively
{
Node cur = root;
for(char c: s)
{
Node nxt = cur.next[c-'a'];
if(nxt == null)
nxt = cur.next[c - 'a'] = new Node();
cur = nxt;
}
cur.val = idx;
}

int search(char[] s)
{
Node cur = root;
for(char c: s)
{
Node nxt = cur.next[c-'a'];
if(nxt == null)
return -1;
cur = nxt;
}
return cur.val;
}
}