感谢 微信平台: 一天一道算法题 ---------------- 每天多一点进步---------------
这题 根据题意 网上终于找到个 相似的题目
原题 给的实在太长了 我给你简短翻译一下:
给定两个长度均为N的字符串( N<=100) 判断它们之间的26个字母能否一一对应 如abb和cdd可以相互对应 方法是a->c b->d
要是相同 输出YES 否则 输出NO
//先去次饭了 回来再写下去。。。。
go on。。。
讲下这题的思路:
既然是字母一一对应的 那么如果是YES的情况下 那么相对应的字母的个数必然是相等的 想到这里 这题就不难了 就是怎么将字符串中每个字母出现的次数保存下来
这边 注意的是 不能忘记了排序 你可能A中 保存了3个a 2个b B中保持了2个c 3个d 要是不进行排序 可能导致2和3 进行比较 就得出了错误的结论
这边它提供了 用 map的做法 看上去 的确 高大上 而且很舒服
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <map> 3 #include <string> 4 #include <cstdio> 5 #include <cstring> 6 #include <algorithm> 7 using namespace std; 8 9 string str1 , str2; 10 int cntA[110]; 11 int cntB[110]; 12 int main() 13 { 14 int len , aLen , bLen; 15 int i; 16 while( cin>>str1>>str2 ) 17 { 18 bool flag = true; 19 memset( cntA , 0 , sizeof(cntA) ); 20 memset( cntB , 0 , sizeof(cntB) ); 21 map<char , int> strA; 22 map<char , int>::iterator itA; 23 map<char , int> strB; 24 map<char , int>::iterator itB; 25 len = str1.length(); 26 for( i = 0 ; i<len ; i++ ) 27 { 28 strA[ str1[i] ]++; 29 strB[ str2[i] ]++; 30 } 31 aLen = strA.size(); 32 bLen = strB.size(); 33 if( aLen!=bLen ) 34 { 35 printf( "NO " ); 36 } 37 else 38 { 39 i = 0; 40 for( itA = strA.begin() ; itA!=strA.end() ; itA++ ) 41 { 42 cntA[ i++ ] = itA->second; 43 } 44 i = 0; 45 for( itB = strB.begin() ; itBstrB.end() ; itB++ ) 46 { 47 cntB[ i++ ] = itB->second; 48 } 49 sort( cntA , cntA+aLen ); 50 sort( cntB , cntB+bLen ); 51 for( i = 0 ; i<aLen ; i++ ) 52 { 53 if( cntA[i]!=cntB[i] ) 54 { 55 flag = false; 56 break; 57 } 58 } 59 printf( "%s ",flag?"YES":"NO" ); 60 } 61 } 62 return 0; 63 }
我自己写了个不用map实现的 代码短了点 但感受还是用map看上去 厉害点。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 6 char strA[110] , strB[110]; 7 int cntA[110] , cntB[110]; 8 9 int main() 10 { 11 int i; 12 bool flag; 13 while( ~scanf("%s %s",strA,strB) ) 14 { 15 flag = true; 16 memset( cntA , 0 , sizeof(cntA) ); 17 memset( cntB , 0 , sizeof(cntB) ); 18 for( i = 0 ; strA[i]!='