PAT-乙-1014 1014 福尔摩斯的约会 (20 分)

PAT-乙-1014 1014 福尔摩斯的约会 (20 分)
PAT-乙-1014 1014 福尔摩斯的约会 (20 分)

代码

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
	
	string str1, str2, str3, str4;
	getline(cin, str1);
	getline(cin, str2);
	getline(cin, str3);
	getline(cin, str4);
	string wek;

	int count = 0;
	int minLen = str1.length()<str2.length()?str1.length():str2.length();
	for(int i=0; i<minLen; i++) {
		if(count>1) {
			break;
		}
		//the first char scope: A-G, not A-Z
		if(count==0 && str1.at(i)>='A' && str1.at(i)<='G') {
			if(str1.at(i)==str2.at(i)) {
				wek = wek + str1.at(i);
				count++;
			}
		} else {
			// the second char scope: 0-9 && A-N
			if(count==1 && str1.at(i)==str2.at(i) &&
			( (str1.at(i)>='0' && str1.at(i)<='9') || (str1.at(i)>='A' && str1.at(i)<='N'))) {
				wek = wek + str1.at(i);
				count++;
			}
		}
	}

	int flag = 1;
	int pos = -1;
	minLen = str3.length()<str4.length()?str3.length():str4.length();
	for(int i=0; i<minLen; i++) {
		if(flag) {
			if(str3.at(i)==str4.at(i)) {
				if( (str3.at(i)>='A' && str3.at(i)<='Z') || (str3.at(i)>='a' && str3.at(i)<='z')) {
					flag = 0;
					pos = i;
					break;
				}
			}
		}
	}

	string week[] = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};
	string hour = "0123456789ABCDEFGHIJKLMN";

	string re = "";
	int pos2 = -1;
	re = re + week[wek.at(0)-'A'] + " ";
	for(int i=0; i<hour.length(); i++) {
		if(hour.at(i)==wek.at(1)) {
			pos2 = i;
			break;
		}
	}

	//output
	cout<<re;
	cout<<setfill('0')<<setw(2)<<pos2<<":"<<setfill('0')<<setw(2)<<pos<<endl;
	return 0;

}

注解

1、仔细理解题意:
第 1 对相同的大写英文字母,代表星期,因此范围只有A-G是合法的,分别代表周一到周日。所谓第1对相同的,就是对应位置字符相同。
第 2 对相同的字符,代表时间,合法范围是0-9和A-N。
后面两字符串第 1 对相同的英文字母,其出现的位置代表分钟,字符串长度不超过60,因此一定合法。
2、需要注意的坑点:
(1)需要求出s1,s2、s3,s4各自的长度最小值,否则在比较时可能会出现数字越界,造成“段错误”或“运行错误”等。
(2)注意各自的合法范围。并不都是A-Z。
3、学到的语法:
(1)getline函数读入一整行:

getline(cin, str1);

(2)cout输出前导0:
首先不要忘记加入头文件iomanip。
要输出前导0,先调用setfill函数设置填充字符,再调用setw函数设置宽度。

#include <iomanip>

cout<<setfill('0')<<setw(2)<<pos2<<":"<<setfill('0')<<setw(2)<<pos<<endl;

结果

PAT-乙-1014 1014 福尔摩斯的约会 (20 分)