转载请注明出处:
题目:
Write a method to decide if two strings are anagrams or not.
翻译:
写一个方法来判断两个字符串是否互为变位词。
注:如果构成两个字符串的字符完全相同,而对应字符所处的位置不同,则称这两个字符串互为变位词。如:"abbfcad"和"facbdab"互为变位词。
思路:
很多人应该一下子就能想到对两个字符串按照在字典中出现的先后顺序进行排序,而后再对排序后的两个字符串逐个比较,如果两个字符串相等,则二者互为变位词,否则,不互为变位词。
事实上,和Q1.1的思路一样,我们同样没有必要对字符串进行排序,我们同样可以利用哈希的思想(到现在为止,四个题目中已经有三个用到了哈希的思想),开辟一个大小为26(假设字符串中的字符为26个小写字母)的int数组,初始值均为0,先对第一个字符串进行映射,每个字符在该字符串中出现一次,数组的对应位置的值就加1,而后再对第二个字符串进行映射,每个字符在该字符串中出现一次,数组中对应位置的值就减1,如果最后该数组的所有元素值均为0,则说明这两个字符串互为变位词。该方法的时间复杂度为O(n)。
实现代码:
/**************************** 题目描述: 判断两个字符串是否互为变位词 Date:2014-03-17 ****************************/ #define MAX 26 #include<iostream> #include<cstring> using namespace std; bool anagram(string s1,string s2) { int len1 = s1.length(); int len2 = s2.length(); if(len1 != len2) return false; int i; int A[MAX]; memset(A,0,sizeof(A)); for(i=0;i<len1;i++) { int index = s1[i] - ‘a‘; A[index]++; } for(i=0;i<len1;i++) { int index = s2[i] - ‘a‘; A[index]--; } for(i=0;i<MAX;i++) if(A[i] > 0) return false; return true; } int main() { string s1 = "abbfcad"; string s2 = "facbdab"; if(anagram(s1,s2)) cout<<"s1 and s2 are anagrams"<<endl; else cout<<"s1 and s2 are not anagrams"<<endl; string s3 = "abbfcad"; string s4 = "facbkab"; if(anagram(s3,s4)) cout<<"s3 and s4 are anagrams"<<endl; else cout<<"s3 and s4 are not anagrams"<<endl; return 0; }测试结果:
【CareerCup】 Arrays and Strings—Q1.4,布布扣,bubuko.com
【CareerCup】 Arrays and Strings—Q1.4
原文:http://blog.csdn.net/ns_code/article/details/21409663