PAT 1036 Boy vs Girls
PAT 1050 String Subtraction
PAT 1071 Speech Patterns
PAT 1036 题解
- 模拟题
string
类型的变量可以通过.empty()
判断是否为控制符串,便于初始化结果变量。
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
string name, gender, id;
int grade;
string f_name, f_id;
int f_grade = -1; // search highest grade.
string m_name, m_id;
int m_grade = 101; // search lowest grade.
for (int i = 0; i < n; i++){
cin >> name >> gender >> id >> grade;
if (gender == "F"){
if (grade > f_grade){
f_grade = grade;
f_name = name;
f_id = id;
}
}else{
if (grade < m_grade){
m_grade = grade;
m_name = name;
m_id = id;
}
}
}
// 分数不经过初始化,可以通过 .empty() 判断字符串是否为空。
if (f_grade == -1){
cout << "Absent" << endl;
}else{
cout << f_name << " " << f_id << endl;
}
if (m_grade == 101){
cout << "Absent" << endl;
}else{
cout << m_name << " " << m_id << endl;
}
if ((m_grade == 101) || (f_grade == -1)){
cout << "NA" << endl;
}else{
int res = f_grade - m_grade;
cout << res << endl;
}
return 0;
}
PAT 1050 题解
哈希表做法时间最优。
- 朴素做法,遍历是
s1
和s2
. unordered_set <char> hash
利用哈希表,时间复杂度为O(1)
。利用.insert()
建立hash表,.count()
查询哈希表是否有某个元素。string 函数: str1.find(str2) .erase(pos, length)
若str1
中不包括str2
,find()
返回string::npos
.
hash表实现
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
string s1, s2;
getline(cin, s1);
getline(cin, s2);
unordered_set <char> hash;
for (auto c: s2) hash.insert(c);
string res;
for (auto c1: s1)
if (!hash.count(c1))
res += c1;
cout << res << endl;
return 0;
}
string函数的实现
#include <iostream>
#include <string>
using namespace std;
int main(){
string s1, s2;
getline(cin, s1);
getline(cin, s2);
for (int i = 0; i < int(s2.size()); i++){
// find() --> O(nm)
while (s1.find(s2[i]) != string::npos){
// erase --> O(n)
s1.erase(s1.find(s2[i]), 1);
}
}
cout << s1 << endl;
return 0;
}
PAT 1071 题解
unordered_map的应用;双指针的应用。
- 读入字符串
- 分离单词
tolower()
转换为小写 - 遍历hash一边寻找出现次数最多的单词
#include <iostream>
#include <unordered_map>
using namespace std;
bool check(char c){
if (c >= '0' && c <= '9') return true;
if (c >= 'A' && c <= 'Z') return true;
if (c >= 'a' && c <= 'z') return true;
return false;
}
int main(){
string str;
getline(cin, str);
unordered_map <string, int> hash;
for(int i = 0; i < int(str.size()); i++){
if (check(str[i])){
int j = i;
string word;
while (j < int(str.size()) && check(str[j])){
word += tolower(str[j++]);
}
hash[word]++;
i = j;
}
}
string words;
int cnt = -1;
for(auto item: hash){
if ((item.second > cnt) || (item.second == cnt && item.first < words)){
words = item.first;
cnt = item.second;
}
}
cout << words << " " << cnt << endl;
return 0;
}
坑边闲话:
- 当要读入整行字符串的时候(包含空格):
// 在 <iostream> 里
getline(char *s, streamsize n, char delim = '\0');
// 在 <string> 里
/*
is : 表示一个输入流,cin
delim : 设置截断字符。
*/
getline(istream& is, string& str, char delim = '\n');
- C++11 关键字
auto
:变量类型自动推断。std=c++11