hihocoder-Week243-hiho字符串app
若是一個字符串剛好包含2個'h'、1個'i'和1個'o',咱們就稱這個字符串是hiho字符串。 spa
例如"oihateher"、"hugeinputhugeoutput"都是hiho字符串。指針
如今給定一個只包含小寫字母的字符串S,小Hi想知道S的全部子串中,最短的hiho字符串是哪一個。code
字符串S blog
對於80%的數據,S的長度不超過1000 內存
對於100%的數據,S的長度不超過100000字符串
找到S的全部子串中,最短的hiho字符串是哪一個,輸出該子串的長度。若是S的子串中沒有hiho字符串,輸出-1。input
happyhahaiohell
5
題解:string
雙指針滑動窗口,先後兩個指針,若是缺乏元素,則前指針前進,若是元素充足,則後指針前進,推動減小窗口。it
#include <cstdlib> #include <cstdio> #include <cstring> const int MAXN = 100000 + 10; char ch[MAXN]; int len, start_id, end_id, ans; int h_num, i_num, o_num; bool check_validation() { return (h_num >= 2 && i_num >= 1 && o_num >= 1); } bool check_ok() { return (h_num == 2 && i_num == 1 && o_num == 1); } void add_item(int idx) { if(ch[idx] == 'h') { h_num += 1; }else if(ch[idx] == 'i') { i_num += 1; }else if(ch[idx] == 'o') { o_num += 1; } } void subtract_item(int idx) { if(ch[idx] == 'h') { h_num -= 1; }else if(ch[idx] == 'i') { i_num -= 1; }else if(ch[idx] == 'o') { o_num -= 1; } } int main(){ scanf("%s", ch); len = strlen(ch); start_id = 0; end_id = 0; h_num = i_num = o_num = 0; ans = len + 1; add_item(start_id); ++start_id; while(end_id < start_id) { if(check_validation() || start_id >= len) { if(check_ok()) { ans = (ans < (start_id - end_id))?(ans):(start_id - end_id); } subtract_item(end_id); ++end_id; }else{ add_item(start_id); ++start_id; } } if(ans > len) { ans = -1; } printf("%d\n", ans); return 0; }