您的位置:首页 > 其它

笔试题 brotherword【tire || hash】

2015-09-07 01:00 176 查看
给定一个单词a,如果通过交换单词中字母的顺序可以得到另外的单词b,那么定义b是a的兄弟单词,例如单词army和mary互为兄弟单词。现在给定一个字典,用户输入一个单词,如何根据字典找出这个单词有哪些兄弟单词?要求时间和空间效率尽可能的高。

方案一:

用hash来做 head中保存的是 排好序的字母顺序 例如 给你bac 那么head中保存的就是abc

然后建立hash表

#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
using namespace std;

const int maxn = 1005;

map<string, int> head;
struct Edge {
string to;
int next;
}e[maxn];
int tot;
void init() {
head.clear();
tot = 1;
}

void add(string s1, string s2) {
e[tot].to = s2;
e[tot].next = head[s1];
head[s1] = tot++;
}

void cal(string s1) {
for(int i = head[s1]; i; i = e[i].next) {
cout << e[i].to << " ";
} puts("");
}

int main() {
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++) {
char s1[10], s2[10];
scanf("\n%s",s1);
strcpy(s2, s1);
int l = strlen(s2);
sort(s2, s2 + l);
string x1 = s2;
string x2 = s1;
add(x1, x2);
}
for(int i = 0; i < n; i++) {
char s1[10], s2[10];
scanf("\n%s",s1);
strcpy(s2, s1);
int l = strlen(s2);
sort(s2, s2 + l);
string x1 = s2;
string x2 = s1;
cal(x1);
}
}


View Code

方案二:

用字典树来做

用字典树建树的时候注意按照排好序的字符串建树,然后在叶子节点上放置改点的原串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: