这道题一开始我的想法是,读出一行,然后根据“-”的位置分成s1和s2.然后按照空格把每一张牌分开存在vector里然后比较。但是忒麻烦了,其实没必要,题目给的条件已经可以很简化了。
首先发现,牌的种类恰好分别是1张,2张,3张,4张,5张。只要出现大小王,那么就输出大小王即可。所以这里不讨论2张中是大小王的情况。那么如果两个人的牌张数相同,那么说明是同一类型。如果张数不一样,说明不是同一类型不能比较,输出ERROR。
!! 张数怎么比较呢?计算空格个数即可。count(str1.begin(), str1.end(), ' ') !!
如果是同一类型,那么只比较第一张大小就可以。
比较的时候因为3和2比较麻烦,所以把牌从小到大按顺序放在一个数组里,通过比较下标的方法确定两张牌哪个大哪个小。
这里注意:得到下标不要忘记减v.begin(): int idx1 = find(v.begin(), v.end(), l1) - v.begin()
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
vector<string> v = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2", "joker", "JOKER" };
string compare(string &s1, string &s2){
int p1 = s1.find_first_of(" ");
int p2 = s2.find_first_of(" ");
string l1 = s1.substr(0, p1);
string l2 = s2.substr(0, p2);
int idx1 = find(v.begin(), v.end(), l1) - v.begin();
int idx2 = find(v.begin(), v.end(), l2) - v.begin();
if(idx1 > idx2) return s1;
else return s2;
}
int main()
{
string str, s1, s2;
while(getline(cin, str)){
int p = str.find_first_of("-");
s1 = str.substr(0, p);
s2 = str.substr(p+1);
if(s1 == "joker JOKER" || s2 == "joker JOKER"){cout << "joker JOKER" << endl; continue; }
int space1 = count(s1.begin(), s1.end(), ' ');
int space2 = count(s2.begin(), s2.end(), ' ');
if(space1 != space2){
if(space1 == 3){cout << s1 << endl; continue; }
if(space2 == 3){cout << s2 << endl; continue; }
cout << "ERROR" << endl; continue;
}
cout << compare(s1, s2) << endl;
}
}