fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone{
  9. public static void main(String[] args) throws java.lang.Exception {
  10. Scanner sc = new Scanner(System.in);
  11. sc.nextInt();
  12. sc.nextLine();
  13. String data = sc.nextLine();
  14. int q = sc.nextInt();
  15. int[][] queries = new int[q][3];
  16. for (int i = 0; i < q; i++) {
  17. queries[i][0] = sc.nextInt();
  18. queries[i][1] = sc.nextInt();
  19. queries[i][2] = sc.nextInt();
  20. }
  21. System.out.println(findDistinctCharacters(data, queries));
  22. }
  23.  
  24. private static List<Integer> findDistinctCharacters(String data, int[][] queries) {
  25. List<Integer> ans = new ArrayList<>();
  26. HashMap<Character, TreeSet<Integer>> map = new HashMap<>();
  27. for (int i = 0; i < 26; i++) {
  28. map.put(((char) ('a' + i)), new TreeSet<>());
  29. }
  30. for (int i = 0; i < data.length(); i++) {
  31. map.get(data.charAt(i)).add(i);
  32. }
  33. StringBuilder s = new StringBuilder(data);
  34. for (int[] query : queries) {
  35. if (query[0] == 1) {
  36. char rep = (char) ('a' + query[2] - 1);
  37. char toReplace = s.charAt(query[1] - 1);
  38. map.get(toReplace).remove(query[1] - 1);
  39. map.get(rep).add(query[1] - 1);
  40. s.setCharAt(query[1] - 1, rep);
  41. } else if (query[0] == 2) {
  42. int left = query[1] - 1;
  43. int right = query[2] - 1;
  44. int distinct = 0;
  45. for (int i = 0; i < 26; i++) {
  46. if (!map.get((char) ('a' + i)).isEmpty()) {
  47. Integer val = map.get((char) ('a' + i)).floor(right);
  48. if (val != null && val >= left
  49. ) {
  50. distinct++;
  51. }
  52. }
  53.  
  54. }
  55. ans.add(distinct);
  56. }
  57.  
  58. }
  59. return ans;
  60. }
  61. }
Success #stdin #stdout 0.14s 54744KB
stdin
7
abccbda
3
2 3 6
1 2 3
2 2 4
stdout
[3, 1]