数组与字符串 1.3

给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。

分析:一个字符串的字符重新排列能变成另一个字符串,要求两个字符串出现的字符类型和数目相同。使用一个数组记录每个字符出现的情况即可。此处假设输入字符为ASCII字符。

 1 #include <iostream>
 2 #include <fstream>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 bool reachable( const char *s, const char *p );
 8 
 9 int main( int argc, char *argv[] ) {
10     string data_file = "./1.3.txt";
11     ifstream ifile( data_file.c_str(), ios::in );
12     if( !ifile.is_open() ) {
13         fprintf( stderr, "cannot open file: %s
", data_file.c_str() );
14         return -1;
15     }
16     string s, p;
17     while( ifile >>s >>p ) {
18         cout <<s <<" " <<p <<": " << boolalpha <<reachable( s.c_str(), p.c_str() ) <<endl;
19     }
20     ifile.close();
21     return 0;
22 }
23 
24 bool reachable( const char *s, const char *p ) {
25     int table[256] = { 0 };
26     int slen = 0, plen = 0;
27     while( s[slen] != '' ) { ++table[s[slen++]];  }
28     while( p[plen] != '' && table[p[plen]] ) { --table[p[plen++]]; }
29     return p[plen] == '' && slen == plen;
30 }

测试文件

aa aa
aa ab
aaa aab
abcdedfg abcdefg
aa11df334 1fd343a1a
abcdefg abcdgds
原文地址:https://www.cnblogs.com/moderate-fish/p/3971460.html