米哈游9.14笔试第一题
找出字符串中存在k个“mihoyo”的最短子串,如果存在,则输出左下标 和右下标,不存在就输出-1, 卡了半个小时了,代码一直25%,求大佬指教指教
#include<iostream> using namespace std; #include<vector> #include<string> int main() { int n, k; cin >> n >> k; string s; cin >> s; string res = "mihoyo"; int count = 0; int l = 0; int r = 0; vector<pair<int, int>>vec; int min_len = INT16_MAX; for (int left = 0; left < n - 5; left++) { string temp = s.substr(left, 6); if (temp == res) { vec.push_back({ left, left + 6 - 1 }); left = left + 5; } } int size = vec.size(); if (size < k) { cout << -1 << endl; return 0; } else { int len = 20000000; for (int i = 0; i < vec.size() - k + 1; i++) { if (vec[i + k - 1].second - vec[i].first < len) { l = vec[i].first; r = vec[i + k - 1].second; } } cout << l <<" "<< r << endl; } return 0; }