Untitled
import java.util.HashMap; class TrieNode { TrieNode[] links; boolean flag; public boolean containsKey(char ch) { return links[ch - 'a'] != null; } public TrieNode get(char ch) { return links[ch - 'a']; } public void put(char ch, TrieNode temp) { links[ch - 'a'] = temp; } public void setEnd() { flag = true; } public boolean isEnd() { return flag; } } public class Main { public static int countDistinctSubstrings(String s) { TrieNode root = new TrieNode(); int cnt = 0; int n = s.length(); for (int i = 0; i < n; i++) { TrieNode temp = root; for (int j = i; j < n; j++) { if (!temp.containsKey(s.charAt(j))) { temp.put(s.charAt(j), new TrieNode()); cnt++; } temp = temp.get(s.charAt(j)); } } return cnt + 1; } public static void main(String[] args) { String s = "striver"; System.out.println("Current String: " + s); System.out.println("Number of distinct substrings: " + countDistinctSubstrings(s)); } }
Leave a Comment