蓝桥——扑克排序 (穷举全排列+check())

题目:

菜鸟代码:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

bool behind(string &s,int p,char a){//Ñ°ÕÒÇ°ÃæÓÐûÓÐÓëaÏàͬµÄ×Ö·û
if(p==0)return false;
for(int i=p-1;i>0;i--){
if(s[i]==a)return true;
}
return false;
}

bool check(string &s){//ÅжÏÊÇ·ñ·ûºÏÒªÇó
int a1=0,a2=0,a3=0,a4=0;
for(int i=0;i<s.length();i++){
int tmp=i;

if(s[i]=='A'&&!behind(s,i,'A')){
do {
a1++;
i++;
}
while(s[i]!='2'&&i<s.length());
i=tmp;
}

if(s[i]=='2'&&!behind(s,i,'2')){
do {
a2++;
i++;
}
while(s[i]!='2'&&i<s.length());
i=tmp;
}

if(s[i]=='3'&&!behind(s,i,'3')){
do{
a3++;
i++;
}
while(s[i]!='3'&&i<s.length());
i=tmp;
}

if(s[i]=='4'&&!behind(s,i,'4')){
do{
a4++;
i++;
}
while(s[i]!='4'&&i<s.length());
i=tmp;
}
}

if(a1==2&&a2==3&&a3==4&&a4==5)return true;
else return false;

}

int main()
{

string s="223344AA";
do{
if(check(s)) cout<<s<<endl;
}while(next_permutation(s.begin(),s.end()));//·µ»ØÏÂÒ»ÖÖ°´×ÖµäÐòÅÅÁÐ

return 0;
}

 

 

做法白痴 结果不对

正确解法:对s.rfind() s.find()的运用 很简单,,,

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;



bool check(string &s){//判断是否符合要求 
 if(s.rfind('A')-s.find('A')==2&&
         s.rfind('2')-s.find('2')==3&&
         s.rfind('3')-s.find('3')==4&&
         s.rfind('4')-s.find('4')==5)
         return true;
         else return false; 
}

int main()
{
    
    string s="223344AA";
    do{
        if(check(s)) cout<<s<<endl;
    }while(next_permutation(s.begin(),s.end()));//返回下一种按字典序排列 
    
    return 0;
}

1.C++中algorithm库next_permutation(s.begin(),s.end())按字母序返回字符串下一种排列 在全排列中经常用到

2.do+check()+while(next_permutation())全排列暴力方法的常用模板

3.s.rfind()从后往前查找s中某一字符的下标 s.find()是从前往后

posted @ 2019-03-10 15:25  Kiss_the_rain  阅读(297)  评论(0编辑  收藏  举报