fork download
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3. #define ld long double
  4. #define mod 1000000007
  5. #define pb push_back
  6. #define ff first
  7. #define ss second
  8. #define mp make_pair
  9. #include<stdio.h>
  10. #define ioS ios::sync_with_stdio(false);
  11. #include<iostream>
  12. using namespace std;
  13.  
  14. ll int power(ll int a,ll int b)
  15. {
  16. if(b==0)
  17. return 1;
  18. else
  19. return a*power(a,b-1);
  20. }
  21. bool sortbya( int l, int r)
  22. {
  23. return(r<l);
  24. }
  25.  
  26. int main()
  27. {
  28. int l;
  29. cin>>l;
  30. string a;
  31. cin>>a;
  32. int posr[l];
  33. int posl[l];
  34.  
  35. for(int i=0;i<l;i++)
  36. {
  37. int fl=0;
  38. for(int j=i+1;j<l;j++)
  39. {
  40. if(a[j]==a[i])
  41. {
  42. posr[i]=j;
  43. fl=1;
  44. break;
  45. }
  46. }
  47. if(fl==0)
  48. {
  49. posr[i]=-1;
  50. }
  51. }
  52.  
  53. for(int i=l-1;i>=0;i--)
  54. {
  55. int fl=0;
  56. for(int j=i-1;j>=0;j--)
  57. {
  58. if(a[j]==a[i])
  59. {
  60. posl[i]=j;
  61. fl=1;
  62. break;
  63. }
  64. }
  65. if(fl==0)
  66. {
  67. posl[i]=-1;
  68. }
  69. }
  70.  
  71.  
  72. /* for(int i=0;i<l;i++)
  73. cout<<posr[i]<<' ';
  74. cout<<endl;
  75.  
  76. for(int i=0;i<l;i++)
  77. cout<<posl[i]<<' ';
  78. cout<<endl;
  79. */
  80. int lef=0,rig=l-1;
  81. int o=0;
  82. while(posr[o]!=-1)
  83. {
  84. lef++;
  85. o++;
  86. }
  87. o=l-1;
  88. while(posl[o]>lef)
  89. {
  90. rig--;
  91. o--;
  92. if(posl[o]==-1)
  93. break;
  94. }
  95. //cout<<lef<<' '<<rig<<endl;
  96. //cout<<rig-lef+1<<endl;
  97.  
  98.  
  99. int lef2=0,rig2=l-1;
  100. o=l-1;
  101. while(posl[o]!=-1)
  102. {
  103. rig2--;
  104. o--;
  105. }
  106. o=0;
  107. while(posr[o]<rig2)
  108. {
  109. if(posr[o]==-1)
  110. break;
  111. lef2++;
  112. o++;
  113. }
  114. //cout<<lef2<<' '<<rig2<<endl;
  115. //cout<<rig2-lef2+1<<endl;
  116.  
  117. cout<<min(rig-lef+1,rig2-lef2+1)<<endl;
  118. return 0;
  119. }
  120.  
  121.  
Success #stdin #stdout 0s 3416KB
stdin
6
aaBCCe
stdout
5