uva 156 - Ananagrams

思路:判断两个单词互为anagram的方法可以将两个单词中字母转成小写,然后按照字母排序,如果排序后两个单词相同,即认为是互为anagram。

 

C++ AC。

/*
 * uva156.cpp
 *
 *  Created on: 2013-4-15
 *      Author: kevinjiang
 */
#include<cstdio>
#include<cstring>
#include<cstdlib>

char words[1005][25];
char lowerCaseWords[2005][25];
int num;

int cmpStr(const void*a, const void*b) {

	return strcmp((char*) a, (char*) b);
}

int cmpChar(const void*a, const void *b) {
	char *aa = (char*) a;
	char *bb = (char*) b;
	return *aa - *bb;

}

int main() {

	char tmp[25];
	for (int i = 0;; i++) {
		scanf("%s", tmp);
		if (tmp[0] == '#') {
			num = i;
			break;
		} else {
			strcpy(words[i], tmp);
		}
	}

	//按字典序排列单词
	qsort(words, num, sizeof(words[0]), cmpStr);

	//大写转小写,然后单词内按字母排序,如果此时两个单词相同,即认为是互为anagram的。
	for (int i = 0; i < num; i++) {
		int len = strlen(words[i]);
		for (int j = 0; j < len; j++) {
			if (words[i][j] >= 'A' && words[i][j] <= 'Z')
				lowerCaseWords[i][j] = words[i][j] + 'a' - 'A';
			else
				lowerCaseWords[i][j] = words[i][j];
		}

		qsort(lowerCaseWords[i],len,sizeof(char),cmpChar);
	}


	for(int i=0;i<num;i++){

		int flag=0;
		for(int j=0;j<num;j++)
			if(i!=j){
				if(!strcmp(lowerCaseWords[i],lowerCaseWords[j]))
					flag=1;
			}

		if(!flag){
			printf("%s\n",words[i]);
		}

	}

	return 0;
}

 

你可能感兴趣的:(uva)