题目地址: http://pat.zju.edu.cn/contests/pat-a-practise/1071
思路比较简单,用map<string, int>来记录,map默认是按字典序的。
但是前几次有两个case TLE了,有可能是用strtok耗时比较长。
先贴一个AC的,用c++的getline来换取一行。
#include<iostream>
#include<string>
#include<cctype>
#include<map>
#include<algorithm>
using namespace std;
int main()
{
int cnt = 0;
string line, max_str;
map<string, int> dm;
map<string, int>::iterator iter;
getline(cin, line);
for(int j = 0; j<line.length(); ++j)
{
if(line[j]>='A' && line[j]<='Z')
{
line[j] += 'a' - 'A';
}
}
int i = 0;
while(i < line.length())
{
while(i < line.length() && !isalnum(line[i]))
{
++i;
}
if(i < line.length())
{
int ibegin = i++;
while(i < line.length() && isalnum(line[i]))
{
++i;
}
if(ibegin < line.length())
{
string str = line.substr(ibegin, i-ibegin);
if(dm.find(str) == dm.end())
{
dm[str] = 1;
}
else
{
++dm[str];
}
}
}
}
for(iter = dm.begin(); iter!=dm.end(); ++iter)
{
if(iter->second > cnt)
{
cnt = iter->second;
max_str = iter->first;
}
}
printf("%s %d\n", max_str.c_str(), cnt);
return 0;
}
下面的用c的字符数组存的,用c的gets来获取一行。
但有两个case 超时了,map上的操作应该差异不大,应该是st rtok,
TLE代码如下
#include<cstdio>
#include<string>
#include<map>
using namespace std;
char line[1048577];
int main()
{
int cnt = 0;
string max_rec_str;
map<string, int> dm;
map<string, int>::iterator iter;
gets(line);
for(int i = 0; i<strlen(line); ++i)
{
if(line[i]>='A' && line[i]<='Z')
{
line[i] += 'a' - 'A';
}
else if((line[i]<'a' || line[i]>'z') &&( line[i] > '9' || line[i]<'0'))
{
line[i] = ' ';
}
}
char* p = strtok(line, " ");
while(p != NULL)
{
iter = dm.find(string(p));
if(iter == dm.end())
{
dm.insert(make_pair(string(p), 1));
}
else
{
iter->second++;
}
p = strtok(NULL, " ");
}
for(iter = dm.begin(); iter!=dm.end(); ++iter)
{
if(iter->second > cnt)
{
cnt = iter->second;
max_rec_str = iter->first;
}
}
printf("%s %d\n", max_rec_str.c_str(), cnt);
return 0;
}
strtok很诡异啊,cplusplus 上这么描述的(http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok):
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
循环的时候注意了,循环里的指针应该赋NULL。
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
另外
int isalnum ( int c );
Check if character is alphanumeric
Checks whether c is either a decimal digit or an uppercase or lowercase letter.
这个函数挺有用的,The result is true if either isalpha or isdigit would also return true.