156 - Ananagrams

题目:156 - Ananagrams


题目:找出单词重排序后和别的单词都不一样的单词


解题思路:只要将每个单词都按从小到大的排序成新的单词


#include<stdio.h>
#include<string.h>
#include<stdlib.h>


const int N = 1005;
const int M = 25;

char ch, word[N][M], w[N][M], tmp[M];
int t = 0, i = 0;

void translate() {

	for(int j = 0; j < t; j++) {
		
		for(int k = 0; k < strlen(w[j]); k++)
			if(w[j][k] >= 'A' && w[j][k] <= 'Z')
				w[j][k] += 32; 

	}
}

int cmp_char (const void * _a, const void *  _b) {
	
	char * a = (char*) _a;
	char * b = (char*) _b;
	return *a - *b;

}

int cmp_string(const void * _a, const void * _b) {
	
	char * a = (char*) _a;
	char * b = (char*) _b;
	return strcmp(a, b);
}

int main() {
	
	int j, k;
	while(scanf("%s", word[t])) {
		
		if(strcmp(word[t], "#") == 0)
			break;
			t++;
	}
	for(i = 0; i < t; i++)
		strcpy(w[i], word[i]);
		translate();

		for( j = 0; j < t; j++) {

				qsort(w[j],  strlen(w[j]), sizeof(char), cmp_char);
		
			}

		qsort(word, t , sizeof(word[0]), cmp_string);

			for( k = 0; k < t; k++) {
				
				int count = 0;
				memset(tmp, 0, sizeof(tmp));
				strcpy(tmp, word[k]);
		
				for(i = 0; i < strlen(tmp); i++)
					if(tmp[i] >= 'A' && tmp[i] <= 'Z')
						tmp[i] += 32;

				qsort(tmp, strlen(tmp), sizeof(char), cmp_char);
		
				for( j = 0; j < t; j++) {

						if(strcmp(tmp, w[j]) == 0)
							count++;
				}
				if(count == 1)
					printf("%s\n", word[k]);

			}
		
	
	return 0;
}

,然后就好判断有没有重复的了。注意要输出原先的单词,所以要保存原先的单词数组,还有输出要排序。scanf()是已回车,空格,‘、\t’作为停止输入的,所以结束之前的数就是一个整体了。



你可能感兴趣的:(156 - Ananagrams)