《编程之法》:兄弟字符串

来源:互联网 发布:数据挖掘项目培训 编辑:程序博客网 时间:2024/05/01 22:12

题目

如果两个字符串中的字符一样,出现次数也一样,只是出现的顺序不一样,则认为这两个字符串是兄弟字符串。如何判断两个字符串是兄弟字符串。

思路

建两个hash数组,分别记录两个字符串,然后比较两个数组的每一项是否相同,有不同的说明不是兄弟字符串。

代码

bool IsBrother(const string a,const string b) {    if (a.length() != b.length()) {        return false;    }    int hashTable1[26] = {0};    int hashTable2[26] = {0};    int n = a.length();    for (int i = 0; i < n; ++i) {        hashTable1[a[i] - 'a']++;        hashTable2[b[i] - 'a']++;    }    for (int j = 0; j < 26; ++j) {        if (hashTable1[j] != hashTable2[j]) {            return false;        }    }    return true;}int main() {    string a = "bad";    string b = "adb";    if (IsBrother(a, b)) {        cout<<a<<" and "<<b<<" are brother"<<endl;    } else {        cout<<a<<" and "<<b<<" are not brother"<<endl;    }    return 0;}

运行结果

bad and adb are brotherProcess finished with exit code 0
0 0
原创粉丝点击