String Graph Matching
InterviewTime limit2sMemory limit1024 MB
Count the substrings of T whose set of adjacent letter pairs is exactly the given set of M directed edges.
- Level
Medium5 of 10
- Topics
- Sliding window, String, Hash map
- Solved
- No attempts yet
Problem
You can build a graph from a string of lowercase letters as follows.
- Create a vertex for each lowercase letter from
atoz. - Write a string of length as . For every positive integer with , add the edge to the graph. If the same edge would be added more than once, add it only once.
Given a graph whose vertices are the lowercase letters and a string , count the substrings of that produce the same graph as the given graph through the process above.
A substring is a string of length at least obtained by cutting some number of characters from the front and some number from the back of a string. For example, for abcde, cd and abc are substrings, but bd is not, because no amount of cutting from the front and back yields it.
Input
The first line contains an integer , the length of the string ().
The second line contains the string , which consists only of lowercase letters and has length .
The third line contains an integer , the number of edges in the graph ().
Each of the next lines contains two lowercase letters with no space between them. The line denotes the directed edge . and may be the same letter. No edge is given more than once.
Output
Print the number of substrings of that produce the same graph as the given graph through the process described above.