hiho #1485 : hiho字符串(滑动窗口)
#1485 : hiho字符串
時間限制:10000ms 單點時限:1000ms 內存限制:256MB描述
如果一個字符串恰好包含2個'h'、1個'i'和1個'o',我們就稱這個字符串是hiho字符串。 ?
例如"oihateher"、"hugeinputhugeoutput"都是hiho字符串。
現在給定一個只包含小寫字母的字符串S,小Hi想知道S的所有子串中,最短的hiho字符串是哪個。
輸入
字符串S ?
對于80%的數據,S的長度不超過1000 ?
對于100%的數據,S的長度不超過100000
輸出
找到S的所有子串中,最短的hiho字符串是哪個,輸出該子串的長度。如果S的子串中沒有hiho字符串,輸出-1。
樣例輸入?
思路:
在給定的字符串S中找到最小的窗口使其完全包含hiho。不能多也不能少,
時間復雜度:O(l1+4)(l1為字符串S的長度)
空間復雜度:O(4)
?
AC代碼:
#include "iostream" #include "string" #include "string.h" #include "vector" #include "map" #include "algorithm"using namespace std;char c[256]; int ans = 100005;int main() {string s;while (cin >> s){memset(c, 0, sizeof(c));int l = s.length();for (int i = 0,j=0; i < l; i++){while (j < l && (c['h'] < 2 || c['i'] < 1 || c['o'] < 1)){c[s[j]]++;j++;if (c['h'] > 2 || c['i'] > 1 || c['o'] > 1)break;}if (c['h'] == 2 && c['i'] == 1 && c['o'] == 1){ans = min(ans, j - i);}c[s[i]]--;}if (ans == 100005)ans = -1;cout << ans << endl;} }?
?
附上LeetCode上一題類似的滑動窗口問題
76. Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S?=?"ADOBECODEBANC"
T?=?"ABC"
Minimum window is?"BANC".
?
代碼:
1 #include "iostream" 2 #include "string" 3 #include "string.h" 4 using namespace std; 5 6 string str; 7 int ans = 100005; 8 9 int count1[256]; 10 int count2[256]; 11 12 string minWindow(string S, string T) { 13 if (T.size() == 0 || S.size() == 0) 14 return ""; 15 16 memset(count1, 0, sizeof(count1)); 17 memset(count2, 0, sizeof(count2)); 18 19 for (int i = 0; i < T.size(); i++) 20 { 21 count1[T[i]]++; 22 count2[T[i]]++; 23 } 24 25 int count = T.size(); 26 27 int start = 0; 28 int minSize = 100005; 29 int minStart; 30 for (int end = 0; end < S.size(); end++) 31 { 32 if (count2[S[end]] > 0) 33 { 34 count1[S[end]]--; 35 if (count1[S[end]] >= 0) 36 count--; 37 } 38 if (count == 0) 39 { 40 while (true) 41 { 42 if (count2[S[start]] > 0) 43 { 44 if (count1[S[start]] < 0) 45 count1[S[start]]++; 46 else 47 break; 48 } 49 start++; 50 } 51 52 if (minSize > end - start + 1) 53 { 54 minSize = end - start + 1; 55 minStart = start; 56 } 57 } 58 } 59 60 if (minSize == ans) 61 return ""; 62 63 string ret(S, minStart, minSize);//string 構造函數 64 return ret; 65 } 66 67 int main() 68 { 69 while (cin >> str) 70 { 71 int l = minWindow(str, "hiho").length(); 72 if (l<4) 73 cout << -1 << endl; 74 else 75 cout << l << endl; 76 } 77 } View Code?
轉載于:https://www.cnblogs.com/SeekHit/p/6623843.html
總結
以上是生活随笔為你收集整理的hiho #1485 : hiho字符串(滑动窗口)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mongo connections ur
- 下一篇: Struts2之Ognl