- 如何讀入整行資料
1
2
| string line; getline(cin, line); |
- 如何轉換為小寫(lowerCase)
1
| transform(line.begin(), line.end(), line.begin(), ::tolower); |
- 如何計算substring頻率
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| int countSubString(const string& sub, const string& str){ if (!sub.length()) return 0; int count = 0; size_t offset; //重疊計算 for (offset=str.find(sub); offset!=string::npos; offset=str.find(sub, offset+1)) count++; /* //不重疊計算 for (offset=str.find(sub); offset!=string::npos; offset=str.find(sub, offset+sub.length())) count++; */ return count; } |
- Sample Code (http://140.114.86.238/problem/9012/)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| #include <cstdio> #include <cstdlib> #include <string.h> #include <math.h> #include <iostream> #include <string> #define MAX 1001 using namespace std; string line[10]; int countSubString(const string& sub, const string& str){ if (!sub.length()) return 0; int count = 0; size_t offset; for (offset=str.find(sub); offset!=string::npos; offset=str.find(sub, offset+1)) count++; return count; } int main(int argc, const char * argv[]) { int n, m, c; string search; while (scanf( "%d %d" , &n, &m)!=EOF) { getchar(); for (int i=0; i< n; i++){ getline(cin, line[i]); transform(line[i].begin(), line[i].end(), line[i].begin(), ::tolower); //printf("%d: %s\n", i, line[i].c_str()); } while (m--) { getline(cin, search); printf( "%s:" , search.c_str()); transform(search.begin(), search.end(), search.begin(), ::tolower); c = 0; for (int i=0; i< n; i++) c += countSubString(search, line[i]); printf( "%d\n" , c); } printf( "\n" ); } return 0;
}
|