标签:nyoj 难度 重复 c/c++ 区间 sub main 代码实现 line
题意很简单,给一个数n 以及一个字符串str,区间【i,i+n-1】 为一个新的字符串,i 属于【0,strlen(str)】如果新的字符串出现过ans++,例如:acmacm n=3,那么 子串为acm cma mac acm ,只有acm出现过
求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; }
标签:nyoj 难度 重复 c/c++ 区间 sub main 代码实现 line
原文地址:https://www.cnblogs.com/GetcharZp/p/8974104.html