nyoj 1112 求次数 (map)
求次数
时间限制:1000 ms | 内存限制:65535 KB
难度:2
- 描述
-
题意很简单,给一个数n 以及一个字符串str,区间【i,i+n-1】 为一个新的字符串,i 属于【0,strlen(str)】如果新的字符串出现过ans++,例如:acmacm n=3,那么 子串为acm cma mac acm ,只有acm出现过
求ans;
- 输入
- LINE 1: T组数据(T<10)
LINE 2: n ,n <= 10,且小于strlen(str);
LINE 3:str
str 仅包含英文小写字母 ,切长度小于10w - 输出
- 求 ans
- 样例输入
-
2 2 aaaaaaa 3 acmacm
- 样例输出
-
5 1
/** 分析:该题是判断 一个字符串中的长度为n的子串重复的次数 方法:map <string, int> || set <string> 模板1 (map): int ans = 0; map <string, int> my_map; pair <map <string, int> :: iterator, bool> pr; for (int i = 0; i <= str.size () - n; ++ i) { sub_str = str.substr (i, n); pr = my_map.insert (pair <string, int> (sub_str, 0)); if (!pr.second) { ++ ans; } } cout <<ans <<endl; 模板2 (set): int ans = 0; set <string> my_set; pair <set <string> :: iterator, bool> pr; for (int i = 0; i <= str.size () - n; ++ i) { sub_str = str.substr (i, n); pr = my_set.insert (sub_str); if (!pr.second) { ans ++; } } cout << ans <<endl; **/
C/C++代码实现 (map):
#include <iostream> #include <algorithm> #include <cstring> #include <cmath> #include <cstdio> #include <stack> #include <queue> #include <map> using namespace std; int main () { int T; scanf ("%d", &T); while (T --) { int n, str_len, ans = 0; string str, mid_str; scanf ("%d", &n); cin >>str; str_len = str.size(); map <string, int> my_map; pair <map <string, int> :: iterator, bool> pr; for (int i = 0; i <=str_len - n; ++ i) { mid_str = str.substr (i, n); pr = my_map.insert (pair <string, int> (mid_str, 0)); if (!pr.second) { ++ ans; } } printf ("%d\n", ans); } return 0; }
C/C++代码实现 (set):
#include <iostream> #include <algorithm> #include <cstring> #include <cmath> #include <cstdio> #include <stack> #include <queue> #include <map> #include <set> using namespace std; int main () { int T; scanf ("%d", &T); while (T --) { int n, str_len, ans = 0; string str, mid_str; scanf ("%d", &n); cin >>str; str_len = str.size(); set <string> my_set; pair <set <string> :: iterator, bool> pr; for (int i = 0; i <=str_len - n; ++ i) { mid_str = str.substr (i, n); pr = my_set.insert (mid_str); if (!pr.second) { ++ ans; } } printf ("%d\n", ans); } return 0; }