Edge Letters

4.8

6 votes
Algorithms, String Algorithms, Basics of String Manipulation, String, Data Structures
Problem

You are given a string S of length N consisting of lowercase english alphabets and you are required to process Q queries. Each query is of the form (ai,bi), where ai and bi are characters from the english lowercase alphabet. You should print the number of substrings of S, whose first character is ai and last character is bi


A substring is obtained by removing a prefix and a suffix of the string. Two substrings si1...sj1 and
si2...sj2 are different if the ordered pair (i1,j1) is different from (i2,j2).

Input Format

  • The first line contains the string S.
  • The second line contains the integer Q, the number of queries.
  • Each of the next Q lines contains two characters ai and bi, separated by a space.

Output Format

For each query, output the number of substrings of S, whose first character is ai and last character is bi.

Constraints

  • 1N105
  • 1Q105
  • The characters in S are all lowercase English letters
Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

In the first query, the substrings starting with 'a' and ending with 'b' are : S1...2 = ab, S1...6 = abacab, S3...6 = acab, S5...6 = ab.

In the second query, the substrings starting with 'b' and ending with 'b' are : S2...2 = b, S6...6 = b, S2...6 = bacab.

Editor Image

?