1. #include<iostream>
    2. #include <string>
    3. #include <set>
    4. #include <map>
    5. using namespace std;
    6. string minW(string s, string t){
    7. int *check = new int['z' + 1];
    8. int *count = new int['z' + 1];
    9. for (int i = 0; i < 'z' + 1; ++i) {
    10. check[i] = 0;
    11. count[i] = 0;
    12. }
    13. int left = -1;
    14. int right = s.length();
    15. int start = 0;
    16. int minLen = s.length() + 1;
    17. for(int i = 0; i < t.length(); i++) check[t[i]]++;
    18. int countNum = 0;
    19. char ch;
    20. for(int i = 0; i < s.length(); i++){
    21. ch = s[i];
    22. if(check[ch] == 0){
    23. continue;
    24. }
    25. if(count[ch] < check[ch]){
    26. // 还没达到
    27. countNum++;
    28. }
    29. count[ch]++;
    30. if(countNum == t.length()){
    31. // 够了
    32. for(int j = start; j < i; j++){
    33. if(check[s[j]] == 0) {
    34. start++;
    35. }
    36. else{
    37. if(count[s[j]] == check[s[j]]){
    38. start = j;
    39. break;
    40. }
    41. else{
    42. count[s[j]]--;
    43. start++;
    44. }
    45. }
    46. }
    47. if(minLen > i - start + 1){
    48. minLen = i - start + 1;
    49. left = start;
    50. right = i;
    51. }
    52. }
    53. }
    54. return left == -1 ? "" : s.substr(left, right + 1 - left);
    55. }
    56. string shortestSubstrAll(string s) {
    57. string minS = "";
    58. set<char> mark;
    59. for (int i = 0; i < s.length(); ++i) {
    60. if (mark.find(s[i]) == mark.end()) {
    61. mark.insert(s[i]);
    62. minS += s[i];
    63. }
    64. }
    65. // 这个temp不是字典序最小
    66. string temp = minW(s, minS);
    67. int len = temp.length();
    68. map<char, int > check;
    69. for (int i = 0; i < len; ++i) {
    70. if (check.find(temp[i]) == check.end()) {
    71. check[temp[i]] = 1;
    72. } else{
    73. check[temp[i]]++;
    74. }
    75. }
    76. // 可以通过找s的长度为len的字串,看看是不是满足条件,找出字典序最小的
    77. for (int i = len; i < s.length() - len + 1; ++i) {
    78. check[s[i - 1]]--;
    79. if (check[s[i - 1]] == 0) {
    80. check.erase(s[i - 1]);
    81. }
    82. if (check.find(s[i + len - 1]) == check.end()) {
    83. check[s[i + len - 1]] = 1;
    84. } else {
    85. check[s[i + len - 1]]++;
    86. }
    87. if (check.size() == len) {
    88. if (s.substr(i, len) < temp) {
    89. temp = s.substr(i, len);
    90. }
    91. }
    92. }
    93. return temp;
    94. }
    95. void t3(){
    96. string s;
    97. cin >> s;
    98. cout << shortestSubstrAll(s) << endl;
    99. }
    100. int main() {
    101. t3();
    102. }