- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
Given two words of equal length that are in a dictionary, write a method to transform
one word into another word by changing only one letter at a time The new word you
get in each step must be in the dictionary
/*
hand
hind
find
for n in all neighbors of src
if(trsf(n, dest)) return true;
*/
int distance(string &s, string &src)
{
if(s.size()!=src.size()) return -1;
int dist = 0;
for(int i; i<src.size(); i++)
{
if(src[i]!=s[i]) dist++;
}
return dist;
}
void neighbors(vector<string> &dict, string &src, vector<string> &nb)
{
for(int i=0; i<dict.size(); i++)
{
if(distance(dict[i], src)==1)
nb.push_back(dict[i]);
}
}
bool trsf(vector<string> &dict, string &src, string &dest)
{
if (src == dest) return true;
vector<string> nb;
neighbors(dist, src, nb);
for(int i=0; i<nb.size(); i++)
{
if(trsf(dist, nb[i], dest)) return true;
}
return false;
}
/*
[LAMP, LIME, LIKE, DAMP, LIMP]
DAMP
LIKE
DAMP => LAMP => =>LIMP => LIME => LIKE
*/