// Java program to implement the above approach
import java.util.*;
public class Main {
// Function to find the first occurrence
// for a given range
public static void firstOccurrence(String s,
ArrayList<Pair<Pair<Integer, Integer>, Character>> Q)
{
// N = length of string
int N = s.length();
// M = length of queries
int M = Q.size();
// Stores the indices of a character
HashMap<Character, ArrayList<Integer>> v
= new HashMap<Character, ArrayList<Integer>>();
// Traverse the string
for (int i = 0; i < N; i++) {
// Push the index i
// into the vector[s.charAt(i)]
char c = s.charAt(i);
if (!v.containsKey(c)) {
v.put(c, new ArrayList<Integer>());
}
v.get(c).add(i);
}
// Traverse the query
for (int i = 0; i < M; i++) {
// Stores the value L
int left = Q.get(i).first.first;
// Stores the value R
int right = Q.get(i).first.second;
// Stores the character C
char c = Q.get(i).second;
if (!v.containsKey(c) || v.get(c).size() == 0) {
System.out.print("-1 ");
continue;
}
// Find index >= L in
// the vector v.get(c)
ArrayList<Integer> charIndices = v.get(c);
int idx = Collections.binarySearch(charIndices, left);
// If there is no index of C >= L
if (idx < 0) {
idx = -(idx + 1);
if (idx == charIndices.size() || charIndices.get(idx) > right) {
System.out.print("-1 ");
continue;
}
}
else if (charIndices.get(idx) > right) {
System.out.print("-1 ");
continue;
}
// Stores the value at idx
idx = charIndices.get(idx);
// If idx > R
if (idx > right) {
System.out.print("-1 ");
}
// Otherwise
else {
System.out.print(idx + " ");
}
}
}
// Driver Code
public static void main(String[] args) {
String S = "abcabcabc";
ArrayList<Pair<Pair<Integer, Integer>, Character>> Q
= new ArrayList<Pair<Pair<Integer, Integer>, Character>>();
Q.add(new Pair<Pair<Integer, Integer>, Character>(new Pair<Integer, Integer>(0, 3), 'a'));
Q.add(new Pair<Pair<Integer, Integer>, Character>(new Pair<Integer, Integer>(0, 2), 'b'));
Q.add(new Pair<Pair<Integer, Integer>, Character>(new Pair<Integer, Integer>(2, 4), 'z'));
firstOccurrence(S, Q);
}
}
class Pair<U, V> {
public U first;
public V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
}
// Contributed by adityashae15